Skip to content

Instantly share code, notes, and snippets.

@christophercliff
Last active April 7, 2016 17:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophercliff/4400464 to your computer and use it in GitHub Desktop.
Save christophercliff/4400464 to your computer and use it in GitHub Desktop.
A Google Chrome Extensions helper class for accessing page context (DOM manipulation, etc.) from the background. Use a node.js-style callback pattern to create a custom page API.
(function(){
chrome.tabs.getSelected(null, function(tab){
var page = new Page(tab);
page.setScrollTo(100, 200, function(err, res){
console.log('You just scrolled the page!');
});
// Or using `async`...
async.parallel([
async.apply(page.setScrollTo, 100, 200),
page.getDocumentSize
], function(err, res){
console.log('You just scrolled the page AND got the document size!');
});
});
})();
{
"manifest_version": 2,
"background": {
"scripts": [
"underscore.js",
"async.js",
"page.js",
"page-api.js",
"background.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": [
"underscore.js",
"page.js",
"page-api.js"
]
}
],
"permissions": [
"http://*/*",
"https://*/*",
"tabs"
]
}
(function(){
_.extend(Page.prototype, {
// Customize this file with your page-specific methods, e.g.
setScrollTo: function (left, top, callback) {
window.scrollTo(left, top);
callback(null);
},
getDocumentSize: function (callback) {
callback(null, {
width: document.body.scrollWidth,
height: document.body.scrollHeight
});
}
});
})();
(function(ctx, isPage){
var send = function (id, name, args, callback) {
chrome.tabs.sendMessage(id, {
name: name,
args: args
}, function(response){
if (response.error)
{
return callback(response.error);
}
callback.apply(null, response.args);
});
};
var Page = function (tab) {
var self = this;
_.bindAll(self);
if (isPage)
{
chrome.extension.onMessage.addListener(function(message, sender, callback){
var method = self[message.name];
if (!_.isFunction(method))
{
return callback({
error: 'Method' + message.name + 'does not exist'
});
}
message.args.push(function(){
callback({
error: null,
args: _.toArray(arguments)
});
});
method.apply(null, message.args);
});
}
else
{
if (!tab)
{
throw new Error('Must reference a tab');
}
_.forEach(Page.prototype, function(val, key){
self[key] = function () {
var args = _.toArray(arguments),
callback = args.pop();
send(tab.id, key, args, callback);
};
});
}
};
if (isPage)
{
new Page();
}
ctx.Page = Page;
})(this, (this.outerWidth > 0 && this.outerHeight > 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment