这是我得到的错误信息:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided
('https://www.youtube.com') does not match the recipient window's origin 
('http://localhost:9000').

我见过其他类似的问题,其中目标源是http://www.youtube.com,收件人源是https://www.youtube.com,但没有一个像我的问题一样,目标是https://www.youtube.com,源是http://localhost:9000。

我不明白这个问题。有什么问题吗? 我该怎么解决呢?


当前回答

确保你从一个URL加载,比如:

https://www.youtube.com/embed/HIbAz29L-FA?modestbranding=1&playsinline=0&showinfo=0&enablejsapi=1&origin=https%3A%2F%2Fintercoin.org&widgetid=1

注意“origin”组件,以及“enablejsapi=1”。原点必须与您的域相匹配,然后它将被列入白名单并工作。

其他回答

当您在调用window.postMessage()时没有指定targetOrigin时,也会收到此消息。

在本例中,我们向第一个iFrame发送消息,并使用*作为目标,这应该允许与任何targetOrigin通信。

window.frames[0].postMessage({
                    message : "Hi there",
                    command :"hi-there-command",
                    data : "Some Data"
                }, '*')

可能有以下任何一种情况,但它们都导致DOM在被javascript访问之前没有加载。

所以在真正调用JS代码之前,你必须确保以下几点: *确保在任何javascript调用之前容器已经加载 *确保目标URL被加载到任何容器中

我遇到了类似的问题,但在我的本地,当我试图让我的Javascript在主页onLoad之前运行良好,导致错误消息。我已经通过简单地等待整个页面加载,然后调用所需的函数来修复它。

你可以简单地通过添加一个超时函数当页面已经加载并调用你的onload事件来做到这一点:

窗口。Onload =新函数(){ setTimeout(函数(){ //一些onload事件 }, 10); }

这将确保你正在尝试的东西将在onLoad触发后很好地执行。

为了避免控制台错误,我使用了类似Artur之前回答的方法来解决这个问题,以下步骤:

Downloaded the YouTube Iframe API (from https://www.youtube.com/iframe_api) to a local yt-api.js file. Removed the code which inserted the www-widgetapi.js script. Downloaded the www-widgetapi.js script (from https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl7VfO1r/www-widgetapi.js) to a local www-widgetapi.js file. Replaced the targetOrigin argument in the postMessage call which was causing the error in the console, with a "*" (indicating no preference - see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). Appended the modified www-widgetapi.js script to the end of the yt-api.js script.

这不是最好的解决方案(修补本地脚本来维护,失去对消息发送位置的控制),但它解决了我的问题。

在使用此解决方案之前,请参阅此处关于删除targetOrigin URI的安全警告- https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

修复了yt-api.js的例子

只需要在播放器的paramVars属性中添加参数“origin”和你网站的URL,就像这样:

this.player = new window['YT'].Player('player', {
    videoId: this.mediaid,
    width: '100%',
    playerVars: { 
        'autoplay': 1,
        'controls': 0,
        'autohide': 1,
        'wmode': 'opaque',
        'origin': 'http://localhost:8100' 
    },
}

我也面临着同样的问题,然后我访问了Youtube官方Iframe Api,在那里我发现了这个:

用户的浏览器必须支持HTML5的postMessage特性。大多数现代浏览器都支持postMessage

而彷徨看到的官方页面也面临着这个问题。只需访问官方Youtube Iframe Api,查看控制台日志。我的Chrome版本是79.0.3945.88。