Last active
December 10, 2018 20:34
-
-
Save jcubic/26f806800abae0db9a0dfccd88cf6f3c to your computer and use it in GitHub Desktop.
Cross domain ajax request without CORS using iframe and postMessage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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) | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think there is a typo there: the function
crossDomainResponse
takes indomain
instead ofurl
.