Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created March 16, 2022 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottoffen/d15ca8fc8094d7267dca941a8c8731eb to your computer and use it in GitHub Desktop.
Save scottoffen/d15ca8fc8094d7267dca941a8c8731eb to your computer and use it in GitHub Desktop.
How to send headers (e.g. authentication tokens) to iframes
<script>
var myIFrame = document.querySelector('#myiframe');
var myUrl = 'http://localhost:1234/api/test';
var myHeaders = [
['Authorization', 'Bearer 1234567890']
];
populateIFrame(myIFrame, myUrl, myHeaders);
function populateIFrame(iframe, url, headers)
{
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'blob';
xhr.withCredentials = true;
headers.forEach(function(header)
{
xhr.setRequestHeader(header[0], header[1]);
});
xhr.send();
function handler()
{
if (this.readyState === this.DONE)
{
if (this.status === 200)
{
iframe.src = URL.createObjectURL(this.response);
}
else
{
console.error('Request failed', this);
}
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment