0

I need to construct some script tags that has variables with params that comes back from an API response. The variables needs to be available in the HTML so it can be accessed after page load. One example of a script needed would be something like this.

<script type="text/javascript">var test_var = "test123";</script>

The current implementation that I have is this

useEffect(() => {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.innerHTML = `var test_var = ${testId};`;
  document.body.appendChild(script);
  return () => {
    document.body.removeChild(script);
  }
}, []);

By doing it that way will the variable be accessible in the HTML of the page since I am technically just setting the whole thing as a string in the script.innerHTML? Upon inspect element it pretty much just shows as

<script type="text/javascript">var test_var = test123;</script>

1 Answer 1

2

Why don't you add it to the window object directly ? Use namespace it to minimise the pollution of the window object

useEffect(() => {
  const MyNameSpace = {
    test_var: testId,
  };
  
  window.MyNameSpace = MyNameSpace;

  return () => {
    delete window.MyNameSpace;
  }
}, []);

Then it will be available to read using window.MyNameSpace or just MyNameSpace in the global scope. You can also use sessionStorage or localStorage

Update

useEffect(() => {
  const newScript = document.createElement("script");
  newScript.setAttribute('type', 'text/javascript');
  const inlineScript = document.createTextNode(`var test_var=${testId}`);
  newScript.appendChild(inlineScript); 
  document.head.appendChild(newScript);

  return () => {
    window.head.removeChild(newScript)
  }
}, []);

Sign up to request clarification or add additional context in comments.

2 Comments

My initial implementation I just added the params that was needed by the third party into the window object directly like what you showed. But they insist that it I have to inject the scripts into the HTML(DOM) inside the body tag. I am not sure of their reasoning behind this.
Updated the answer based on that

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.