Created
March 16, 2022 21:02
-
-
Save scottoffen/d15ca8fc8094d7267dca941a8c8731eb to your computer and use it in GitHub Desktop.
How to send headers (e.g. authentication tokens) to iframes
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
<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