David Ferris
David Ferris

Reputation: 2325

Javascript/HTML: Create and execute header script from string

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.

Upvotes: 0

Views: 729

Answers (2)

Orinayo Oyelade
Orinayo Oyelade

Reputation: 347

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>
      ...
    </>
)

Upvotes: 2

ihormillion
ihormillion

Reputation: 84

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);

Upvotes: 0

Related Questions