1

I have a src tag in my HTML which includes a private API key. I didn't want to use the key in the HTML so I made a config.js file so I could reference it from there instead.

<script src="main.js"></script>
<script src="config.js"></script>
var token = '12345'

Later, I have to reference in key in the URL and I tried doing this:

<script async defer
  src=`https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`>
 </script>

The URL is underlined red, but shows no error message. I was wondering how I would go about doing this. Thanks!

1
  • What's the ultimate purpose? This would be almost the same level of security ("none"). Commented Dec 17, 2021 at 7:25

2 Answers 2

1

Construct the <script> tag dynamically in JavaScript once you have the token.

const script = document.body.appendChild(document.createElement('script'));
script.src = `https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`;
Sign up to request clarification or add additional context in comments.

2 Comments

If I have two source JavaScript files, how would the HTML know which to use. The purpose of my config file was to just store the token to reference it. Sorry if this is a trivial question, I'm very new to JS
Variables you declare on the top level of any non-module file will be available anywhere.
1

Make an html element in javascript and append it to the head Index.html:

<script defer src="scriptTagConfig.js"></script>

scriptTagConfig.js:

//Create element
const apiScriptTag = document.createElement("script")

//Set src attribute
apiScriptTag.setAttribute("src",`https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`)

//Append to DOM
document.head.appendChild(apiScriptTag)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.