Calling a script snippet by id in a React SPA and content only loads on refresh

802 Views Asked by At

Working on a React application that makes use of a 3rd party JS script from OneTrust cookie scripts. Their scripts really are not designed well for SPAs. Right now I’m simply calling the script section by ID within a div and nothing else as the entire script is parked elsewhere within the project - nothing fancy there. I have a simple CookiePolicy.jsx component like below:

const CookiePolicy = () => {
    return <div id=“cookieHTMLSnippet” />
}

The snippet provides a load of text and some tables based on the HTML of the parent script. The parent script could be called something like cookie-policy.js

The issue is it only loads the content on page reload. I don’t have much code to share but I can only think of doing something weird with getElementById, somehow connect some state to it and place it within a useEffect and force the content to load using dangerouslySetInnerHTML. Is there a simpler, more elegant way to approach this issue? I’m sure I’m not the only one struggling with 3rd party scripts in a SPA...

As a note, in this scenario changing the placement of the script or where I’m calling this ID itself is not an option.

2

There are 2 best solutions below

0
adsy On

You can try synthetically triggering the events it listens to (I've made an educated guess below) -- but it's hacky and could well have a knock-on effect with other scripts that could be listening. If it's a script you don't control, check the dev docs thoroughly as often these things put a global function on window you can call to force it to check the DOM again. Sometimes it's undocumented. Check window in dev tools for anything populated by this script.

That would be preferable, but if not:

const CookiePolicy => {
    // Layout effect waits for DOM to render
    useLayoutEffect(() => {
          dispatchEvent(new Event('load'))
          dispatchEvent(new Event('DOMContentLoaded'))
    }, [])

    return (
        return <div id=“cookieHTMLSnippet” />
    );
}

0
Shane Luca On

Thanks for the comments guys and appreciate the suggestion @adsy!

There was an exposed function(initializeCookiePolicyHtml) I missed the first time around that generates the HTML which made this much simpler.

Ended up implementing it like this:

  useEffect(() => {
    typeof window.OneTrust !== 'undefined' && window.OneTrust.initializeCookiePolicyHtml(true)
  }, [])
  return <div id="cookieHTMLSnippet" />
}```