views:

59

answers:

1

Long story short I'm working on a Google Chrome Extension. The extensions don't have access 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.

A: 

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.

Prestaul
Thanks, that's what I was trying in effect. Not sure why it wasn't working, I wonder if it was because I was trying to use appendChild rather than just setting the .text attribute.
Brad