Reputation: 103849
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!
Upvotes: 3
Views: 2536
Reputation: 103849
So it seems the answer is you can't, due to security restrictions :(
I had to hack my way around it by using an iframe
(oddly, the iframe
can access its parent document).
Upvotes: 1
Reputation: 103849
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...
Upvotes: 2
Reputation: 111265
I bet the script just isn't loaded when you call it right away, does this work:
<script src="..."></script><script>setTimeout(function() {console.log(SomeObject)}, 3000)</script>
Upvotes: 1