Loading third party script within functional component in React site

81 Views Asked by At

I spent way too many hours on this problem, which seems to be something trivial, and I can not understand where is my mistake.

I bought terms and conditions from Termly.com and I want to display those terms and conditions on my website.

My App.js:

function App() {

  return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="terms" element={<TermsScreen />} />
        <Route path="privacy" element={<PrivacyScreen />} />
      </Routes>
  );
}

My PrivacyScreen.js:

const PrivacyScreen = () => {
    const [cookies, setCookie] = useCookies(['viewed_cookie_policy']);
    return (
    <div className="App">
      <Header />
      <Privacy />
            {!cookies.viewed_cookie_policy ? <Consent /> : null}
    </div>
    );
};

// Default export
export default PrivacyScreen;

My Privacy.js file is exactly the same as in termly website (apart from my own credentials):

const Privacy = () => {

  useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://app.termly.io/embed-policy.min.js";
    script.async = true;
    document.body.appendChild(script);
  }, []);  return (
    <div
      name="termly-embed"
      data-id="myid"
      data-type="iframe"
    ></div>
  );
};

// Default export
export default Privacy;

The error which I get (onc I navigate to the priacy page) is:

Uncaught runtime errors:
×
ERROR
Script error.
    at handleError (http://localhost:3000/static/js/bundle.js:111308:58)
    at http://localhost:3000/static/js/bundle.js:111327:7

 Uncaught TypeError: Cannot read properties of null (reading 'postMessage')
    at VM275 embed-policy.min.js:172:32577

Also, this is the rror which Iget on the console:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://app.termly.io') does not match the recipient window's origin ('http://localhost:3000').

The script eventually loads (I see it behind the error) but I can not fix this error. I tried many things, using Helmet as well, but I still keep getting different errors. Can someone please edvice.

My Privacy.js using Helmet (in this case I dont have any errors but nothing is loading):

return (
    <Helmet>
       <meta charSet="utf-8" />
        <link rel="canonical" href="https://app.termly.io/document/privacy-policy/my-id" />
    </Helmet>
  )
1

There are 1 best solutions below

0
newbie coder On

I answered the question myself via this url:

My edited code:

const loadScript = () => {
    const script = document.createElement("script");
    script.src = "https://app.termly.io/embed-policy.min.js";
    script.async = true;
    script.id = "embed-policy";
    document.head.appendChild(script);
};


  if (typeof window === "undefined") {
    return null;
  }

  if (document.getElementById("embed-policy") === null) {
    loadScript();
  }

Hopefully, it will help someone.