javascript - 将 iframe 内容设置为从 fetch 命令返回值

标签 javascript html iframe embed

我想在我的 html 页面上将 iframe 的内容设置为来自 js 中的 fetch 命令的响应。我目前正在使用此代码。

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();
});

当我测试这段代码时,iframe 只显示


   [Object Response]

我想在 iframe 中看到嵌入的 YouTube 视频。

最佳答案

data 是您需要等待的 promise 对象或另一个 then

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

但是还有一个问题,响应头没有Access-Control-Allow-Origin所以你不能读取响应。并且 mode: 'no-cors' 不会绕过 CORS。

关于javascript - 将 iframe 内容设置为从 fetch 命令返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66328421/

相关文章:

android - targetSdkVersion 24 的 Webview 出错

iframe - 当我更改 GWT 应用程序的 html 文件中的 document.domain 属性时,出现空白页

javascript - 在 iFrame 中定义 customElements 会抛出 "DOMException: Operation not supported"。为什么?

javascript - 尝试使用 puppeteer 根据文本/innerText 内容返回单个按钮

javascript - 在 PHP 中从 JSON_decode 数组访问值

jquery按顺序从上到下淡出

html - 将鼠标悬停在 div A 上并更改 div B

javascript - 在 highcharts 上更改 y 轴

javascript - 我应该使用 [innerHTML] 还是通常的方式(Angular 2)

html - 删除 IE 10 兼容性 View 中的蓝色边框