这是我得到的错误信息:

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。

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


当前回答

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

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

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

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

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

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

其他回答

我想我们可以定制YT的sendMessage。球员

playerOptions.playerVars.origin = window.location.origin or your domain.
this.youtubePlayer = new YT.Player(element,playerOptions);
this.youtubePlayer.sendMessage = function (a) {
   a.id = this.id, a.channel = "widget", a = JSON.stringify(a);
   var url = new URL(this.h.src), origin = url.searchParams.get("origin");
   if (origin && this.h.contentWindow) {
       this.h.contentWindow.postMessage(a, origin)
   }
}

我在我的项目中使用了这个函数来求解。

删除DNS预取可以解决此问题。

如果你使用WordPress,在主题的functions.php中添加这一行

remove_action( 'wp_head', 'wp_resource_hints', 2 );

我的是:

<youtube-player
  [videoId]="'paxSz8UblDs'"
  [playerVars]="playerVars"
  [width]="291"
  [height]="194">
</youtube-player>

我只是用playerVars删除了这一行,它在主机上没有错误。

只需要在播放器的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' 
    },
}

你可以改变你的iframe像这样,并添加原点为您当前的网站。它解决了我浏览器上的错误。

<iframe class="test-testimonials-youtube-group"  type="text/html" width="100%" height="100%"
  src="http://www.youtube.com/embed/HiIsKeXN7qg?enablejsapi=1&origin=http://localhost:8000"
  frameborder="0">
</div>

裁判:https://developers.google.com/youtube/iframe_api_reference # Loading_a_Video_Player