Wednesday, January 5, 2011

Using JQuery AJAX Calls in a Chrome Plugin

Chrome really fights cross site scripting like the plague, whether you are building a plugin or not. Some of us love the simplicity of the JQuery AJAX functions and want to use them in our content scripts instead of the ugly XMLHttpRequests. If you throw one in, you will get a "Origin https://mail.google.com is not allowed by Access-Control-Allow-Origin" error.Use the code below to enable $.post, $.get, $.ajax, and $.post. 



In your background page, include the following JS. What this is doing is adding a listener for the partiular functions (you specify which in your request), and funneling the request through your jquery libarary (notice, we add it in the beginning). 



 








Then to the top of your content scripts, add these functions that work as proxies:




_getJSON = function(url, callback) {
console.log("calling JSON");
chrome.extension.sendRequest({action:'getJSON',url:url}, callback);
}
_ajax = function(url, callback, type, async) {
console.log("calling ajax");
chrome.extension.sendRequest({action:'ajax',url:url, type:type, async:async}, callback);
}

_get = function(url, callback) {
console.log("sending get");
chrome.extension.sendRequest({action:'get',url:url}, callback);
}

_post = function(url, data, callback) {
console.log("sending post");
chrome.extension.sendRequest({action:'post', data: data, url:url}, callback);
}



 



If you would like more of the functionality from the functions, you need to pass them from your content script. Add them as parameters in the proxy functions. 



That's it, enjoy plugin development!