I would like to set the content of an iframe on my html page to the response from a fetch
command in js. I am currently using this code.
JavaScript
x
15
15
1
window.fetch(
2
"https://www.youtube.com/embed/SXR0D3MzpBM?autoplay=0&mute=1", {
3
method: 'GET',
4
accept: 'text/html',
5
mode: 'no-cors'
6
})
7
.then(data => {
8
console.log(data);
9
10
var iframe = document.getElementById('video');
11
iframe.contentWindow.document.open();
12
iframe.contentWindow.document.write(data);
13
iframe.contentWindow.document.close();
14
});
15
When i test this code, the iframe just displays
JavaScript
1
2
1
[Object Response]
2
I would like to see an embedded youtube video in the iframe.
Advertisement
Answer
data
is promise object you need to await or another then
JavaScript
1
4
1
.then(async (data) => {
2
data = await data.text();
3
..
4
but there is another problem, the response headers doesn’t have Access-Control-Allow-Origin
so you can’t read the response. and the mode: 'no-cors'
wont bypass CORS.