Next.js Discord

Discord Forum

How to inject js script to head/body without modifying codebase?

Unanswered
Siamese Crocodile posted this in #help-forum
Open in Discord
Siamese CrocodileOP
Hi all,

Quick use-case into:

I'm building a figma like editor for react/next apps. The app clones arbitrary next/react codebase in a container and runs the dev-server. Dev-server is exposed via proxy to iframe.

One of the features of the app is interactive component selector in the iframe. Very similar to selecting elements in react app via React Dev Tools.

This is all done by adding a .js script into head or body. The script will hook into DOM, add bunch of event listeners and communicate outside of the iframe via postMessage (https://www.locatorjs.com/ does something very similar).

Now the problem

How can I add/inject the .js script into the codebase programatically without user/developer intervention.

I have tried several things
- Webpack plugin that hooks into PROCESS_ASSETS_STAGE_OPTIMIZE stage, checks for some common chunk names (e.g. main, main-app) and updates the content of the chunk with my script. This plugin is added to next config programatically.
- Tried to create or update _document.js, layoyt.js or extend some other common react/next apps with the script automatically.

Both of these approaches work but they are not ideal.

Is there anything that comes to your mind that would help me inject the script?
Would it be possible to achieve this via swc plugin?

I'm thankful for any tips/pointers/recommendations/opinions 🙏

2 Replies

const script = document.createElement("script")
script.src = "..."
document.querySelector('head').appendChild(script)
run this in a useEffect