Created
May 5, 2015 19:47
-
-
Save lances101/b4e05ad849312077e413 to your computer and use it in GitHub Desktop.
Javascript CrossDomain Workaround
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
/* | |
* 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