Skip to content
Advertisement

Set iframe content to return value from fetch command

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.

window.fetch(
        "https://www.youtube.com/embed/SXR0D3MzpBM?autoplay=0&mute=1", {
    method: 'GET',
    accept: 'text/html',
    mode: 'no-cors'
})
.then(data => {
    console.log(data);

    var iframe = document.getElementById('video');
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(data);
    iframe.contentWindow.document.close();
});

When i test this code, the iframe just displays

   [Object Response]

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

.then(async (data) => {
    data = await data.text();
.....

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement