YouTube Iframe API 无法 post 消息到 http。收件人有来源 https

YouTube Iframe API Unable to post message to http. Recipient has origin https

使用 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 等)中也能正常工作。而且,事实证明它只在一台特定的机器上坏了。它确实适用于另一台机器 运行 相同 OS 和浏览器。

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

生成的 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 网址中),但随后我收到警告说:

Untrusted origin: http://example.com

(因为主站服务器在http)

如何解决这个问题?

我确实看到了这个相关问题:

从哪里开始调试?

只需将 <embed> URL 更改为 https://:

<iframe id="myVideo" frameborder="0" allowfullscreen="1" title="YouTube video player"
        width="200" height="200" src="https://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>
<!----------------------------------------^

原因是,在 http:// 上加载 https:// 内容是可以的,但反之则不行。最后,如果这不起作用,您可以随时使用 CloudFlare 的免费 SSL 代理。

不要使用 <script src='path/to/iframe_api'></script> 标记加载 YouTube Iframe API,而是使用他们在 documentation:

中推荐的方式

此代码异步加载 IFrame 播放器 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);

实际上,从JavaScript端创建script标签,不要直接放在HTML端(例如<script src="..."></script>)。