Executing code in the webpage context from Chrome extensions
Posted: February 11th, 2012 | Author: shesek | Filed under: Javascript | Tags: Chrome, chrome content script, chrome extension, webpage context | No Comments »Content scripts on Chrome extensions run on a different context than the page they’re running on. They can access and manipulate the DOM, but they don’t have access to any variables of functions defined in the webpage.
It is, however, possible to inject new <script> tags into the page and execute code from there. Yet, passing data from the content script scope and getting data back isn’t very convenient – which is why I wrote a small function to make that easier.
To pass data into the webpage context, the inject function takes a function as its last arguments and passes all the arguments preceding it to that function. To get data back from the webpage context I’m taking advantage of the fact that appendChild is synchronous and blocks execution until the script is finished executing by replacing the <script> innerText with the return value.
Do note that all the data is exchanged in JSON format, so only primitive values and simple array/objects can be passed. When the code causes an exception, its stringified and thrown in the content script context (a magic isException property is used for that, so be careful not to use it for other purposes).
Here’s the function (written in CoffeeScript. For those of you still using JavaScript, the JavaScript version is available at the gist):
The usage:
Hope you found that useful. Enjoy.