I'm adding a script to my page:
<script src="https://example.com/script.js"/>
But I would like to be able to pass a "key" to this script as it's being loaded, the key needs to be accessible by the loaded script, as it depends on it.
How can I do this?
Ideally something like this would be great:
<script src="https://example.com/script.js?key=authkey"/>
But I can't find much on getting this to work.
So far I've been adding an extra meta tag:
<meta
name="key"
content={"authkey"}
/>
And accessing it from the script:
const key = document.getElementsByName("key")[0].content;
But this isn't great. I also found this answer but it's not much better.
You can create new Element script pass its src as your shown link and append in body
window.addEventListener("load", () => {
const script = document.createElement("script")
script.src = "https://example.com/script.js"
document.body.appendChild(script)
const meta = document.createElement("meta")
meta.name = "key"
meta.content = "authkey"
document.getElementsByTagName('head')[0].appendChild(meta)
const key = document.getElementsByTagName("meta")[0]
console.log(key.name)
})
Edited: I couldn't add key property as attribute if I wouldn't use setAttribute("key", "key"), I used that method but appeared another problem
when I was grabbing that meta tag from document.head, it was showing that added Element, I also could print its content but not key, maybe because meta tag's default attribute isn't key, attributes that you can pass there are only charset, content, http-equiv and name, when I was printing key.name it was returning "undefined", and then I changed key to name and worked perfectly, if attribute name doesn't cause problem for you everything works well