How to add Request Headers to an IFrame src request
July 28, 2021
In this blog post, you'll learn how to send a request header while fetching an iframe.
One possible use case for this method is, that you can send an authentication token (JWT) to your iframe URL.
The Solution
Since there is no HTML-Only solution for this problem we'll need some JavaScript.
Here is an simple vanilla JS example:
<iframe></iframe>
<script>
async function getSrc() {
const res = await fetch("http://example.com/someiframe", {
method: 'GET',
headers: {
// Here you can set any headers you want
}
});
const blob = await res.blob();
const urlObject = URL.createObjectURL(blob);
document.querySelector('iframe').setAttribute("src", urlObject)
}
getSrc();
</script>
So what's happening here?
- We fetch the iframe using the Fetch API.
- We use the Response.blob() method which returns a promise that resolved into a Blob. The Blob object allows us to store the iframe as raw data.
- Using the URL.createObjectUrl() method and the Blob as an argument, we create an object URL which is then inserted as the source of our iframe.