Can the src attribute of an iframe perform a POST request?

Viewed 7650

I need to load an iframe using a src attribute. There is a lot of additional information I need to attach to the query. Currently, I just put all this information in a parameter like so:

<iframe src="mywebsite.com/get_iframe?aVeryLongString"></iframe>

However, aVeryLongString can get very long. So long that I get a "414 (Request-URI Too Large)" error from the server.

Is there a way to make this request without getting this error?

Note: The url of the iframe comes with its own Content-Security-Policy, so I can't just use srcdoc instead of src. Unless there is a way to force the CSP even if you use srcdoc?

1 Answers

If the iframe will contain HTML, I would lean toward doing what Scott marcus mentioned in a comment: Doing an ajax POST and populating a div rather than using an iframe.

But if you can't do that for whatever reason (and there could be several reasons you couldn't, not least if the iframe will have content other than HTML):

If aVeryLongString is in the standard URI-encoded name1=value1&name2=value2 form, you can give the iframe a name, and then POST a form to it from JavaScript code. Very roughly:

<iframe name="the-iframe"></iframe>
<script>
(function() { // Scoping IIFE to avoid creating global vars
    var form, input;
    form = document.createElement("form");
    form.action = "/path/to/the/resource"; // I didn't use your `src` because it's incorrect
    form.target = "the-iframe";
    for (/*...looping through the fields you need to add...*/) {
        input = document.createElement("input");
        input.type = "hidden";
        input.name = /*...the field name...*/;
        input.value = /*...the field value...*/;
        form.appendChild(input);
    }
    document.body.appendChild(form);
    form.submit();
})();
</script>

Side note: src="mywebsite.com/get_iframe" is incorrect, the URL would be //mywebsite.com/get_iframe (a protocol-relative URL) or, if the page is being loaded from that site, /get_iframe or possibly ./get_iframe.

Related