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

时间:2016-04-11 06:52:55

标签: javascript iframe youtube safari youtube-iframe-api

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

  

无法向http://www.youtube.com发送消息。收件人来源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网址中),但后来我收到警告说:

  

Untrusted origin: http://example.com

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

如何解决这个问题?

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

从哪里开始调试?

1 个答案:

答案 0 :(得分:3)

请勿使用<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);

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