Running a script containing `document.write` inside a React component

Precursor: I’ve been asked to implement a 3rd party widget which is loaded through a script tag.

This script is implemented by placing <script src="https://some.domain/script.js" /> where you want it to be executed. It writes the widget to that section of the DOM on load; including loading some jquery libraries.

Script start:

  document.write("<!–- jQuery and jQuery UI are a required...

The script contains a form, which includes a dynamic token, so it’s not something I can just replicate as jsx.

I’ve tried using an iFrame, which works up to submission, whereupon the 3rd party page attempts to open. This happens, not in a new tab, but inside the iFrame. Not only that, but X-Frame-Options are set to sameorigin. So, even if I could possibly make an iFrame solution work, it ends up not working.

Since document.write is not going to work in React, options like react-helmet, react-load-script, or hooks are out.

I’m hoping there’s a way to achieve this which doesn’t involve getting devs from this 3rd party vendor involved to work around the issues (deadline looming).

Any guidance?


I’ve requested my 3rd party provider update their approach. document.write has been under the microscope for quite some time and using it at this point in time just doesn’t cut it. More info:

Avoid document.write() # Remove all uses of document.write() in your code. If it’s being used to inject third-party scripts, try using asynchronous loading instead.

If third-party code is using document.write(), ask the provider to support asynchronous loading.