Skip to content

Instantly share code, notes, and snippets.

@jcubic
Last active December 10, 2018 20:34
Show Gist options
  • Save jcubic/26f806800abae0db9a0dfccd88cf6f3c to your computer and use it in GitHub Desktop.
Save jcubic/26f806800abae0db9a0dfccd88cf6f3c to your computer and use it in GitHub Desktop.
Cross domain ajax request without CORS using iframe and postMessage
$.fn.crossDomainRequest = function(url, method, data, fn) {
var self = this;
var receiver = self.attr('src').replace(/\/.*$/, '').replace(/^https?::\/\//, '');
function get(event) {
if (event.origin.match(receiver)) {
// event.data is response from POST
fn(event.data);
}
}
if (window.addEventListener){
addEventListener("message", get, false)
} else {
attachEvent("onmessage", get)
}
var payload = JSON.stringify({url: url, method: method, data: data);
self[0].contentWindow.postMessage(payload, self.attr('src'));
};
$.crossDomainResponse = function(url) {
function listener(event) {
if (event.origin.match(domain.replace(/\./g, '\\.'))) {
var data = JSON.parse(event.data);
$[data.method](data.url, data.data, function(reponse) {
window.parent.postMessage(reponse, "*");
});
}
}
if (window.addEventListener){
addEventListener("message", listener, false)
} else {
attachEvent("onmessage", listener)
}
};
}
// in sender.com
var iframe = $('<iframe/>').attr('src', 'http://reciver.com/cross-domain').hide().appendTo('body');
iframe.crossDomainRequest('/some/page', 'get', {}, function(response) {
console.log(response);
});
// in reciver.com
$.crossDomainResponse('sender.com');
@myTerminal
Copy link

I think there is a typo there: the function crossDomainResponse takes in domain instead of url.

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