[javascript] Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

This is the error message that I get:

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').

I've seen other similar problems where the target origin is http://www.youtube.com and the recipient origin is https://www.youtube.com, but none like mine where the target is https://www.youtube.com and the origin is http://localhost:9000.

  1. I don't get the problem. What is the problem?
  2. How can I fix it?

The answer is


There could be any of the following, but all of them lead into DOM not loaded before its accessed by the javascript.

So here is what you have to ensure before actually calling JS code: * Make sure the container has loaded before any javascript is called * Make sure the target URL is loaded in whatever container it has to

I came across the similar issue but on my local when I am trying to have my Javascript run well before onLoad of the main page which causes the error message. I have fixed it by simply waiting for whole page to load and then call the required function.

You could simply do this by adding a timeout function when page has loaded and call your onload event like:

window.onload = new function() { setTimeout(function() { // some onload event }, 10); }

that will ensure what you are trying will execute well after onLoad is trigger.


You can save the JavaScript into local files:

Into the first file, player_api put this code:

if(!window.YT)var YT={loading:0,loaded:0};if(!window.YTConfig)var YTConfig={host:"https://www.youtube.com"};YT.loading||(YT.loading=1,function(){var o=[];YT.ready=function(n){YT.loaded?n():o.push(n)},window.onYTReady=function(){YT.loaded=1;for(var n=0;n<o.length;n++)try{o[n]()}catch(i){}},YT.setConfig=function(o){for(var n in o)o.hasOwnProperty(n)&&(YTConfig[n]=o[n])}}());

Into the second file, find the code: this.a.contentWindow.postMessage(a,b[c]);

and replace it with:

if(this._skiped){
    this.a.contentWindow.postMessage(a,b[c]); 
}
this._skiped = true;

Of course, you can concatenate into one file - will be more efficient. This is not a perfect solution, but it's works!

My Source : yt_api-concat


I think the description of the error is misleading and has originally to do with wrong usage of the player object.

I had the same issue when switching to new Videos in a Slider.

When simply using the player.destroy() function described here the problem is gone.


You can try :

document.getElementById('your_id_iframe').contentWindow.postMessage('your_message', 'your_domain_iframe')

You could change your iframe to be like this and add origin to be your current website. It resolves error on my browser.

<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>

ref: https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player


In my case this had to do with lazy loading the iframe. Removing the iframe HTML attribute loading="lazy" solved the problem for me.


Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:

  1. Downloaded the YouTube Iframe API (from https://www.youtube.com/iframe_api) to a local yt-api.js file.
  2. Removed the code which inserted the www-widgetapi.js script.
  3. 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.
  4. 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).
  5. Appended the modified www-widgetapi.js script to the end of the yt-api.js script.

This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.

Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Patched yt-api.js example


It looks it's only a Chrome security system to block repeated requests, using CORB.

https://www.chromestatus.com/feature/5629709824032768

In my case, YouTube was blocking Access after the first load of the same webpage which has many video API data request, high payload.

For pages with low payload, the issue does not occur.

In Safari and other non Chronuim based browsers, the issue does not occur.

If I load the webpage in a new browser, the issue does not occur, when I reload the same page, the issue appears.


Just add the parameter "origin" with the URL of your site in the paramVars attribute of the player, like this:

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' 
    },
}

Make sure you are loading from a URL such as:

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

Note the "origin" component, as well as "enablejsapi=1". The origin must match what your domain is, and then it will be whitelisted and work.


You also get this message when you do not specify a targetOrigin in calls to window.postMessage().

In this example we post a message to the first iFrame and use * as target, which should allow communication to any targetOrigin.

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

Remove DNS Prefetch will solve this issue.

If you're using WordPress, add this line in your theme's functions.php

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

mine was:

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

I just removed the line with playerVars, and it worked without errors on console.


Adding origin=${window.location.host} or "*" is not enough.

Add https:// before it and it will work.

Also, make sure that you are using an URL that can be embedded: take the video ID out and concatenate a string that has the YouTube video prefix and the video ID + embed definition.


This exact error was related to a content block by Youtube when "playbacked on certain sites or applications". More specifically by WMG (Warner Music Group).

The error message did however suggest that a https iframe import to a http site was the issue, which it wasn't in this case.


I was also facing the same issue then I visit official Youtube Iframe Api where i found this:

The user's browser must support the HTML5 postMessage feature. Most modern browsers support postMessage

and wander to see that official page was also facing this issue. Just Visit official Youtube Iframe Api and see console logs. My Chrome version is 79.0.3945.88.


I had this same problem and it turns out it was because I had the Chrome extension "HTTPS Everywhere" running. Disabling the extension solved my problem.


Try using window.location.href for the url to match the window's origin.


Setting this seems to fix it:

  this$1.player = new YouTube.Player(this$1.elementId, {
    videoId: videoId,
    host: 'https://www.youtube.com',

In my instance at least this seems to be a harmless "not ready" condition that the API retries until it succeeds.

I get anywhere from two to nine of these (on my worst-case-tester, a 2009 FossilBook with 20 tabs open via cellular hotspot).... but then the video functions properly. Once it's running my postMessage-based calls to seekTo definitely work, haven't tested others.


I got the same error. My mistake was that the enablejsapi=1 parameter was not present in the iframe src.


In some cases (as one commenter mentioned) this might be caused if you are moving the player within DOM, like append or etc..


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to youtube

Youtube - downloading a playlist - youtube-dl YouTube Autoplay not working How to embed new Youtube's live video permanent URL? How do you use youtube-dl to download live streams (that are live)? How can I get the actual video URL of a YouTube live stream? YouTube: How to present embed video with sound muted ffprobe or avprobe not found. Please install one Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Examples related to youtube-api

How can I get the actual video URL of a YouTube live stream? Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN' Google OAUTH: The redirect URI in the request did not match a registered redirect URI YouTube API to fetch all videos on a channel How do I get video durations with YouTube API version 3? Youtube API Limitations Stop embedded youtube iframe? How can I get a channel ID from YouTube? Embed YouTube Video with No Ads

Examples related to youtube-iframe-api

YouTube: How to present embed video with sound muted Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 How to remove youtube branding after embedding video in web page?