首页 > 解决方案 > 对于在 html 中使用 iframe 循环,Spotify 播放按钮

问题描述

我正在尝试制作一个 for 循环,为我放入特定列表中的每个 URI 显示 Spotify 播放按钮。因此,如果此专辑spotify:album:08Cq2FeFxRQdpkKrjCGrth在列表中,它将显示为

<iframe src="https://open.spotify.com/embed/album/08Cq2FeFxRQdpkKrjCGrth" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>

因此 for 循环会将 URI 放入iframe标记中。

这是我的以下代码,我已经在网上查看了许多教程和示例,但无法弄清楚这种情况。

var list = ["spotify:album:08Cq2FeFxRQdpkKrjCGrth"];
for (var i = 0; i < list.length; i++) {
    var source = list[i].split(":")[2];
    var iframe = document.createElement("iframe");
    iframe.src = source;
    iframe.width = "300";
    iframe.height = "380";
    iframe.frameborder = "0";
    iframe.allowtransparency = "true";
    iframe.allow = "encrypted-media";
    document.getElementById("demo").appendChild(iframe);
}

标签: javascripthtmlarraysfor-loop

解决方案


这是我想出的。但是您需要将其部署到服务器才能工作,否则即使您添加了沙箱,无论如何您都会收到此错误。这需要使用正确的 http/https url 部署到服务器(没有本地或 ipaddress url 将起作用)

embed.2019-01-15_bcdc2b81.js:1 Uncaught DOMException: Failed to read the 'cookie' property from 'Document': The document is sandboxed and lacks the  

var list = ["spotify:album:1DFixLWuPkv3KT3TnV35m3"];
var url = "https://embed.spotify.com?uri="
for (var i = 0; i < list.length; i++) {
    var source =url + list[i]
    var iframe = document.createElement("iframe");
    iframe.src = source;
    iframe.width = "300";
    iframe.height = "380";
    iframe.frameborder = "0";
    iframe.allowtransparency = "true";
    iframe.allow = "encrypted-media";
    document.getElementById("demo").appendChild(iframe);
    
}
iframe{
border:1px solid red;
width:100%;
height:100%;
}
<div id="demo"></div>


推荐阅读