Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created November 26, 2016 06:47
Show Gist options
  • Save akirattii/6facb74b9987e17728dc5958c344adc5 to your computer and use it in GitHub Desktop.
Save akirattii/6facb74b9987e17728dc5958c344adc5 to your computer and use it in GitHub Desktop.
cross-domain post form using iframe
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