Skip to content

Instantly share code, notes, and snippets.

@lances101
Created May 5, 2015 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lances101/b4e05ad849312077e413 to your computer and use it in GitHub Desktop.
Save lances101/b4e05ad849312077e413 to your computer and use it in GitHub Desktop.
Javascript CrossDomain Workaround
/*
* Just a simple javascript cross domain workaround.
* The typical <script> hack with a little bit of sugar
* Needs a unique value to identify the callback
* in the callback stack when the script completes.
* The uniqueId is not generated outside because it needs to be passed
* as a parameter in the API call
* The callback stack is stored in window.crossDomainCallbacks
*/
function crossDomainScript(url, uniqueId, callback) {
var script = (document.createElement("SCRIPT"));
script.id = uniqueId;
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
if (!window.crossDomainCallbacks) {
window.crossDomainCallbacks = [];
}
window.crossDomainCallbacks[uniqueId] = function (res) {
callback(res);
script.parentElement.removeChild(script);
};
}
//example usage, needs working API url though
function crossDomainExample(){
var uniqueId = Math.random().toString(36).slice(2);
crossDomainScript("http://somewebsite/api/doSomething?callback=window.crossDomainCallbacks['" + uniqueId + "']",
uniqueId, function(){
alert("Callback successful!")
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment