Created
July 5, 2013 07:35
-
-
Save jackprice/5932698 to your computer and use it in GitHub Desktop.
Use a hidden iframe to send data. Useful for bypassing cross-origin request restrictions where you don't need to know the response, just to send the data.
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
/** | |
* Send data to a URL using a hidden iframe | |
* @param {String} URL The URL to send to | |
* @param {Object} data An object describing the data to send (optional) | |
* @param {String} method The method (GET / POST) (optional) | |
*/ | |
function sendData(URL, data, method){ | |
/* Check we have a URL to send to */ | |
if (typeof URL != "string"){ | |
return; | |
} | |
/* Create a hidden iframe to use to submit the data */ | |
var iframe = document.createElement("iframe"); | |
iframe.setAttribute("style", "display: none"); | |
iframe.setAttribute("name", "iframe-da39a3ee-5e6b4b0d-3255bfef-95601890-afd80709"); | |
/* Create a hidden form to set our data in */ | |
var form = document.createElement("form"); | |
form.setAttribute("action", URL); | |
form.setAttribute("method", typeof method == "undefined" ? "GET" : method); | |
form.setAttribute("style", "display: none"); | |
form.setAttribute("target", "iframe-da39a3ee-5e6b4b0d-3255bfef-95601890-afd80709"); | |
document.body.appendChild(form); | |
/* Create hidden inputs for our data */ | |
for (var key in data){ | |
var input = document.createElement("input"); | |
input.setAttribute("name", key); | |
input.setAttribute("value", data[key]); | |
form.appendChild(input); | |
} | |
/* Submit it! */ | |
form.submit(); | |
} | |
/** | |
* Example use: | |
* | |
* sendData("http://www.google.com", {"foo": "bar"}, "GET"); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment