Ben Coe (@benjamincoe)
ImageMaily lets you right-click on an image on a webpage and send it to an email address.
Background Pages
Context Menus
Content Scripts
Background.prototype.createContextMenuItem = function() {
var _this = this;
chrome.contextMenus.create({
type: 'normal',
title: 'Mail Image',
contexts: ['image'],
onclick: function(info, tab) {
_this.messages[tab.id].push({
imageUrl: info.srcUrl
});
}
});
};
In the content script:
setInterval(function() {
chrome.extension.sendRequest(request, function(response) {
if (!response) return;
if (typeof(response) == 'string') {
alert(response);
} else {
imageUrl = response.imageUrl;
$( "#dialog-form" ).dialog( "open" );
}
});
request = {};
}, 200);
In the background script:
// Returning data from queue.
if (typeof(_this.messages[sender.tab.id]) == 'undefined') _this.messages[sender.tab.id] = [];
if (_this.messages[sender.tab.id].length > 0) {
callback(_this.messages[sender.tab.id].pop());
} else {
callback(false);
}
});
// Populating the queue from an XHR request.
Background.prototype.sendEmail = function(request, tab) {
var _this = this;
if (typeof(_this.messages[tab.id]) == 'undefined') _this.messages[tab.id] = [];
$.ajax({
type: 'get',
url: 'http://localhost',
data: {
imageUrl: request.imageUrl,
email: request.email
},
success: function(response) {
if (response.success) {
_this.messages[tab.id].push( _this.successMessage );
} else {
_this.messages[tab.id].push( _this.failureMessage );
}
},
error: function() {
_this.messages[tab.id].push( _this.failureMessage );
}
});
};
The server, written in Node.js, handles downloading the image and emailing it.
app.get('/', function(req, res){
var imageUrl = req.param('imageUrl'),
filename = ( imageUrl.match(/^.*\/([^/]*)$/)[1] ).match(/([^?&]*)/)[1];
downloadImage(imageUrl, function(imageData) {
sendMail(imageData, filename, req.param('email'), function(err, success) {
res.contentType('application/json');
if (err) {
res.send({
success: false
});
} else {
res.send({
success: true
});
}
});
});
});
If approached in a sane, methodical way Chrome Extension development can be a fun paradigm to work within. Building extensions is a great way to get more users for your SaaS offering.