Long story short I'm working on a Google Chrome Extension. The extensions don't have a开发者_如何学编程ccess to variables in the scope of the page they are operating on by default (you need to communicate through the DOM).
What I'm trying to do is insert a script into the page; this works fine by defining a script tag and a src attribute.
The problem is this script needs a variable to be initialized beforehand. In order to initialize this variable I'm trying to construct a script element with its code inline (rather than loaded from an external source) but I'm having trouble getting it to work.
Is this possible and if so, how do I define the source inside the script? I've tried appending a text-node containing the JS source to the script element but to no avail.
It sucks, but the best way to do this is probably to communicate your data by injecting it into the DOM: http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication
You also might be able to accomplish this by doing something like:
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'alert("It works!");';
document.head.appendChild(script);
I haven't tested this, but I'm guessing it will work from your content scripts.
精彩评论