0

I have a React app where I allow the user to specify <script> tags to be added as HTML headers. These are fetched after the document has loaded, and are stored as plain text properties (I can't just point <script src="//some-location... because it's a string, not a file). I have tried several things but nothing is working.

let json = loadDataFromServer();
console.log(json.headerHTML); // prints <script type="text/javascript">alert("Header script working");</script>

// This just appends it as a string to the header.
document.getElementsByTagName("head")[0].append(json.headerHTML);

enter image description here

// This appends the script tags properly, but doesn't run the script.
document.head.innerHTML = document.head.innerHTML + json.headerHTML;

enter image description here

It may be worth mentioning that this is part of a React app, but as far as I know dangerouslySetInnerHTML() cannot be used in the header, only body HTML.

1
  • For the purposes of this question, I am ignoring the obvious XSS problems this poses. Commented Oct 28, 2020 at 19:47

2 Answers 2

2

react-helmet may help achieve this. You can strip away the opening and closing script tag from the server's response and concatenate the header content as shown below.

import {Helmet) from 'react-helmet'

...
return (
    <>
      <Helmet>
        {json.headerHTML ? (
          <script>
            {`
              ${json.headerHTML}
            `}
          </script>
        ) : null}
      </Helmet>
      ...
    </>
)

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

Comments

0

It's pretty simple. You need to create a DOM element and append it to the head.

const element = document.createElement('script');
element.innerHTML += 'alert("hello");'
document.head.appendChild(element);

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.