0

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.

lpetrucci
  • 1,285
  • 4
  • 22
  • 40
  • 2
    _But I can't find much on getting this to work..._ What issues are you facing? Where is the corresponding code? – B001ᛦ Sep 29 '21 at 13:01
  • 1
    Does this help? [How may I reference the script tag that loaded the currently-executing script?](https://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) – Felix Kling Sep 29 '21 at 13:02
  • 1
    The issue is that there's no way that I've found to actually access the query string from within the script. – lpetrucci Sep 29 '21 at 13:02
  • 1
    Does this answer your question? [Passing parameters to JavaScript files](https://stackoverflow.com/questions/2190801/passing-parameters-to-javascript-files) – DevWithZachary Sep 29 '21 at 13:03
  • `new URL(document.currentScript.src).searchParams` could work. – Felix Kling Sep 29 '21 at 13:04
  • `document.currentScript` is `null` for me. I will try the other answers. – lpetrucci Sep 29 '21 at 13:07

1 Answers1

1

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

callmenikk
  • 1,358
  • 2
  • 9
  • 24