-1

Say I have the following code:

in my content-script.js:

const script = document.createElement('script');

script.setAttribute("type", "application/javascript");
script.src = chrome.runtime.getURL('inject.js');
(document.head || document.documentElement).appendChild(script);

And then in my inject.js

window.addEventListener('message', (event) => {
    console.log(event)
}

This does not print anything to the console. Now I know that the inject script is working as when I open the popup window from it, that functions as expected. How can I go about debugging the injected script? Where can I see it's stdout?

Abraham P
  • 15,029
  • 13
  • 58
  • 126
  • 1) Don't use `script` element as it may run too late after the site already sent the event or broke addEventListener and console.log. Use registerContentScripts as shown [here](https://stackoverflow.com/a/72607832). 2) To see the script in devtools sources you can add a dummy sourcemap comment at the last line. – wOxxOm Feb 05 '23 at 11:32

1 Answers1

0

Output from a script injected in this way should show in the Dev Tools console as normal. If it isn't, one thing to check could be the "Selected context only" option above the console, which if checked limits which contexts output is shown from.

enter image description here

Another possibility of course is that there isn't a message event being fired on the page - you could replace the console.log with something like an alert to confirm if that's the case.

One last thing worth checking - make sure the script is exposed under the web_accessible_resources manifest key. Without this, the script will fail to load: https://developer.chrome.com/docs/extensions/mv3/manifest/web_accessible_resources/

Oliver Dunk
  • 484
  • 5
  • 12
  • Not true. Dynamic script can in injected without a web_accessible_resources in manifest. – Perry Jun 16 '23 at 21:00