Executing code in the webpage context from Chrome extensions

Posted: February 11th, 2012 | Author: | Filed under: Javascript | Tags: , , , | 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.


Chrome desktop notifications for GitHub

Posted: July 30th, 2011 | Author: | Filed under: General | Tags: , , , , , , | No Comments »

I’ve been looking for something to notify me about new GitHub notifications, and didn’t find anything. As I also wanted to take a look at the desktop notifications API, I decided to write a small Chrome extension that displays GitHub’s notifications as desktop notifications.

There’s no API or feed to get those notifications from, so I ended up scraping that data from the HTML page using XmlHttpRequest. The options page lets you set the interval for checking for new notifications.

You can browse the source at github.com/shesek/github-notifications, or download the packed extesntion here. Released under WTFPL 2.0.