Created
November 26, 2016 06:47
-
-
Save akirattii/6facb74b9987e17728dc5958c344adc5 to your computer and use it in GitHub Desktop.
cross-domain post form using iframe
This file contains hidden or 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
| let url = "http://example.host/"; // target to post form | |
| let params = [ | |
| { name: "a", value: encodeURIComponent("1") }, | |
| { name: "b", value: encodeURIComponent("2") }, | |
| ]; | |
| crossDomainPost(url, params); | |
| function crossDomainPost(url, params) { | |
| // Add the iframe with a unique name | |
| let iframe = document.createElement("iframe"); | |
| let uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING"; | |
| document.body.appendChild(iframe); | |
| iframe.style.display = "none"; | |
| iframe.contentWindow.name = uniqueString; | |
| // construct a form with hidden inputs, targeting the iframe | |
| let form = document.createElement("form"); | |
| form.target = uniqueString; | |
| form.action = url; | |
| form.method = "POST"; | |
| addParams2Form(params, form); | |
| document.body.appendChild(form); | |
| form.submit(); | |
| function addParams2Form(arr, form) { | |
| arr.forEach(function(item) { | |
| let input = document.createElement("input"); | |
| input.type = "hidden"; | |
| input.name = item.name; | |
| input.value = item.value; | |
| form.appendChild(input); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment