javascript - YouTube Iframe API 无法将消息发布到 http。收件人有来源 https

标签 javascript iframe youtube safari youtube-iframe-api

使用 YouTube Iframe API,我在 Safary 9.1、OS X Yosemite 中收到以下错误。

Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com

该页面在其他浏览器(例如 Firefox、Chrome 等)中也能正常工作。而且,事实证明它只在一台特定的机器上坏了。它确实可以在另一台运行相同操作系统和浏览器的机器上运行。

我不知道从哪里开始调试它。

生成的 iframe HTML 代码如下所示:

<iframe id="myVideo" frameborder="0" allowfullscreen="1" title="YouTube video player" width="200" height="200" src="http://www.youtube.com/embed/?html5=1&amp;showinfo=0&amp;autoplay=0&amp;rel=0&amp;controls=1&amp;playsinline=1&amp;enablejsapi=1&amp;origin=http%3A%2F%2Fwww.example.com"></iframe>

JavaScript 代码是这样的:

...
vid_frame = new YT.Player(id, {
    height: '200',
    width: '200',
    videoId: id,
    playerVars: {
       html5: 1,
       showinfo: showVideoInfo,
       autoplay: 0,
       rel: showRelatedVideos,
       controls: showPlayerControls,
       playsinline: 1
    },
    events: {
        onReady: onPlayerReady
    }
});

我觉得有一个浏览器设置阻止了网站和 YouTube API 之间的通信,但错误只是说 https://www.youtube.com 正在尝试向 http://www.youtube.com(而不是 https)。

我尝试手动将 http 更改为 https(在 iframe url 中),但随后我收到警告:

Untrusted origin: http://example.com

(因为主网站是通过 http 的服务器)

如何解决这个问题?

我确实看到了这个相关问题:Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com

从哪里开始调试?

最佳答案

不要使用 <script src='path/to/iframe_api'></script> 加载 YouTube Iframe API标签,但使用他们在 documentation 中推荐的方式:

此代码异步加载 IFrame Player API 代码。

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

事实上,创建script来自 JavaScript 端的标记,不要将其直接放在 HTML 中(例如 <script src="..."></script> )。

关于javascript - YouTube Iframe API 无法将消息发布到 http。收件人有来源 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36541737/

相关文章:

html - 通过 iframe、vimeo 或自托管实现视频?

javascript - 从多级跨域 iframe 确定顶级窗口的 url

javascript - Firefox 上的 Flexslider 和 YouTube Iframe API 出现问题 ("* is not a function")

apache-flex - 弹性 : streaming video from YouTube

javascript - 嵌入代码 youtube 视频时 Jw 播放器错误

javascript - 按两个输入值之间的范围过滤元素的菜单

javascript - 正则表达式返回 NaN 的 JS 对象类型

javascript - 如何用css或js隐藏文本?

java - SpringMVC之clientSide view技术处理JsonResponse

jquery - 从 iframe 中重新加载父窗口