<@U07FJ89LFFB> can I inyect a JS script to modify ...
# ask-ai
w
@brash-pillow-71627 can I inyect a JS script to modify the DOM of a test?
o
A message from kapa.ai
Yes, you can inject a JavaScript script to modify the DOM in a GrowthBook experiment. GrowthBook's Visual Editor supports adding custom JavaScript, which is executed as quickly as possible—often before the page has fully loaded. This allows you to implement complex changes to the DOM as part of your experiment. If your script needs to wait for certain elements to appear, GrowthBook recommends using a helper function like the following:
Copy code
js function waitFor(selector) {     return new Promise(resolve => {       const el = document.querySelector(selector);       if (el) return resolve(el);       const observer = new MutationObserver(() => {           const el = document.querySelector(selector);           if (el) { observer.disconnect(); resolve(el)}       });       observer.observe(document, {childList: true, subtree: true});     });   }  // Usage example: waitFor(".my-element").then((el) => {     el.innerHTML = "Hello World!";   });
This approach gives you flexibility to modify the DOM as needed for your test. Just ensure your code accounts for the timing of when elements are available on the page [Custom JavaScript – Visual Editor](https://docs.growthbook.io/app/visual#custom-javascript). If you are using the Visual Editor to inject custom JavaScript, be aware that your site's Content Security Policy (CSP) may need to allow
unsafe-inline
and
unsafe-eval
for the script to run. There are also advanced options using nonces, but these require additional configuration [Deploying to Production – Visual Editor](https://docs.growthbook.io/app/visual#deploying-to-production). In summary: Yes, you can inject JS to modify the DOM in a test using GrowthBook's Visual Editor.