Skip to content

Instantly share code, notes, and snippets.

@romannurik
Created September 24, 2009 05:15
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save romannurik/192538 to your computer and use it in GitHub Desktop.
Save romannurik/192538 to your computer and use it in GitHub Desktop.
A workaround for Cross-domain XHR's not working in Chrome Extensions' content scripts. See http://groups.google.com/group/chromium-extensions/browse_thread/thread/43ec4d383cf8d01d
<!DOCTYPE html>
<html>
<head>
<script src="xhrproxy.js"></script>
<script>
setupXHRProxy();
</script>
</head>
</html>
...
proxyXHR({
method: 'GET',
url: 'http://bar.com/external.js',
onComplete: function(status, data) {
if (status == 200) {
alert(data);
} else {
alert("HTTP Error " + status + " while retrieving data.");
}
}
});
...
...
"background_page": "background.html",
"content_scripts": [
{
"matches": ["http://foo.com/*"],
"js": ["xhrproxy.js", "content-script.js"]
}
],
"permissions": [
"http://bar.com/"
]
...
var XHR_PROXY_PORT_NAME_ = 'XHRProxy_';
/**
* Should be called by the background page.
*/
function setupXHRProxy() {
chrome.extension.onConnect.addListener(function(port) {
if (port.name != XHR_PROXY_PORT_NAME_)
return;
port.onMessage.addListener(function(xhrOptions) {
var xhr = new XMLHttpRequest();
xhr.open(xhrOptions.method || "GET", xhrOptions.url, true);
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
port.postMessage({
status: this.status,
data: this.responseText,
xhr: this
});
}
}
xhr.send();
});
});
}
/**
* Should be called by the content script.
*/
function proxyXHR(xhrOptions) {
xhrOptions = xhrOptions || {};
xhrOptions.onComplete = xhrOptions.onComplete || function(){};
var port = chrome.extension.connect({name: XHR_PROXY_PORT_NAME_});
port.onMessage.addListener(function(msg) {
xhrOptions.onComplete(msg.status, msg.data, msg.xhr);
});
port.postMessage(xhrOptions);
}
@Nou4r
Copy link

Nou4r commented Aug 18, 2016

Works fine, if i load it via tampermonkey.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment