Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: Injecting external script

I'm creating a Chrome extension that appends a script tag to a page, and then uses code defined in that external script:

$('body').append('<script src="..."></script><script>console.log(SomeObject)</script>');

SomeObject is defined in the external script, so I should be able to access it, right? Well, I can't, as I get an "undefined" error.

I even tried using head.js to load the external script and execute a function after the script is loaded, to no avail.

If I open the Chrome console, I can access the damn object just fine!!!

I tried both a content script and executeScript inside a background page to no avail. On both, if I use console.log(window), I can inspect the window object in the console, and SomeObject is nowhere to be found. If I inspect the window object on the Chrome console, there it is!

Are injected scripts sandboxed somehow or what gives?

Thanks!

like image 919
Ivan Avatar asked Mar 06 '26 14:03

Ivan


1 Answers

This is what finally worked:

var script = document.createElement('script');
script.src = "...";
script.addEventListener('load', function() {
  // SomeObject is available!!!
});
document.head.appendChild(script);

I wonder why none of the other methods worked...

like image 186
Ivan Avatar answered Mar 09 '26 03:03

Ivan