244

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?
Adam Zerner
  • 17,797
  • 15
  • 90
  • 156
  • 1
    possible duplicate of [Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')](http://stackoverflow.com/questions/22194409/failed-to-execute-postmessage-on-domwindow-the-target-origin-provided-does) – Leo Feb 27 '15 at 16:26
  • 5
    I had the same issue, and the fix below by @ChrisFranklin fixed it for me; but what's weird is that with my issue, I would only get the error about half the time, and even then the video would still load (though other things would break). – dgo Apr 06 '16 at 15:12
  • 3
    @dgo same issue, it was random on page load. Turns out (I think) its due to the actual iframe contents not being fully ready by the time something else is attempting to do a postMessage. So its a race condition. And if the postMessage happens at a later time (user action), it works fine without error. – IncredibleHat Jun 25 '19 at 19:29
  • 12
    **even Google has that error itself** - open console and play the video here: https://developers.google.com/youtube/iframe_api_reference – T.Todua Jun 21 '20 at 20:11
  • This is happening on my shopify store. I used to dabble in web design back in the day but that was before all this crazy stuff going on now lol (before smart phones even). Anyone know why this would happen to a shopify store? I'm just using one of their updated themes so I would think it wouldn't have any errors. The only embeds I have are social media and they all use https so idk why it's having this problem. – Wayne Filkins Mar 07 '23 at 20:40

29 Answers29

117

I believe this is an issue with the target origin being https. I suspect it is because your iFrame url is using http instead of https. Try changing the url of the file you are trying to embed to be https.

For instance:

'//www.youtube.com/embed/' + id + '?showinfo=0&enablejsapi=1&origin=http://localhost:9000';

to be:

'https://www.youtube.com/embed/' + id + '?showinfo=0&enablejsapi=1&origin=http://localhost:9000';
Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109
Chris Franklin
  • 3,864
  • 2
  • 16
  • 19
  • 2
    That seems to have worked. Thanks! So the problem is `http` vs. `https`? It doesn't matter that the domains differ (youtube vs. localhost)? And what exactly is target origin vs. recipient origin? How did doing what you said change the recipient origin (my url is still localhost:9000)? – Adam Zerner Dec 19 '14 at 21:52
  • 37
    The error is a little misleading. It actually has nothing to do with you being on `localhost:9000`. The problem was actually in the way you were using the youtube-api. When you declare the api as `tag.src = "https://www.youtube.com/iframe_api";` in your code, you are telling youtube you want to use ssl. So, the change I suggested changed you to using ssl to request the videos. The error was just saying you were mixing ssl and non-ssl calls. – Chris Franklin Dec 19 '14 at 21:56
  • 13
    I came across this issue when I tried to move the iframe around in the dom. `playerEl = document.querySelector('iframe#ytplayer'); anotherEl.appendChild(playerEl); // yt complains on subsequent api calls` – posit labs Nov 30 '15 at 22:11
  • Hi @ChrisFranklin I am getting the same error on all channel Ids except for one provided in this app ( https://creatorup.com/build-mobile-app-for-your-youtube-channel-with-ionic2-and-angular2/ ), what could be the reason for this? Thanks for any kind of help... (Y) – Haris Dec 12 '16 at 18:43
  • 1
    what if I'm using javascript to load YouTube player? – N3R4ZZuRR0 Jan 16 '17 at 15:09
  • 13
    changed to https:// for youtube and my domain is https:// still not solve my problem. Failed to execute ‘postMessage’ on ‘DOMWindow’: The target origin provided (‘https://www.youtube.com’) does not match the recipient window’s origin (‘https://test.dev’). – vee Apr 04 '17 at 06:40
  • @andy-mccullough . have you found a solutuion ? I am stuck with same issue, I have http everywhere. – ishandutta2007 Apr 06 '17 at 04:07
  • and @deelux too ? – ishandutta2007 Apr 06 '17 at 04:07
  • @ishandutta2007 I found that there are 2 things maybe cause of this error message. 1 is ``. 2 is jQuery was loaded in the `` section while YouTube API and js that works on YouTube API loaded in the bottom of `` section. If I move jQuery to the bottom of `` and remove `dns-prefetch` it has no error. But I'm using WordPress so, I don't have an idea to fix it then I just leave it like this. – vee Apr 06 '17 at 05:38
  • 4
    This doesn't fix the problem – Simon Gamble Aug 04 '21 at 06:30
43

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' 
    },
}
kyrsquir
  • 51
  • 6
Flávio
  • 486
  • 4
  • 5
24

Setting this seems to fix it:

  this$1.player = new YouTube.Player(this$1.elementId, {
    videoId: videoId,
    host: 'https://www.youtube.com',
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
M.Ali El-Sayed
  • 1,608
  • 20
  • 23
12

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

Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109
Artur
  • 211
  • 2
  • 6
  • Fixed it for me. Had the files locally anyway so fit my use case. – frequent Mar 04 '18 at 20:54
  • This worked for me too, but I'm not sure why. Can you explain why this fixes it? – jchavannes Jan 19 '19 at 23:33
  • 1
    thank you, answered my question on second ajax call: https://stackoverflow.com/questions/58232081/youtube-video-not-playing-in-second-ajaxcall – Diogo Almeida Oct 09 '19 at 13:23
  • On my point of view, using local file for library, in particular for third party service library, is a very bad way to code. No ? – Damien C Mar 19 '20 at 10:19
  • @DamienC It's less than ideal for sure. But, based on all of the other "fixes" on this thread, I'm not surprised (nor do I really judge) other developers changing the API code manually. – Erutan409 Jul 07 '20 at 14:23
  • In 2020 this also fixed it for me. I also add this line playerVars: {'autoplay': 1,'origin': pathname}, path name being => let pathname = window.location.href; – Marcos J.D Junior Mar 20 '21 at 10:49
7

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.

Gregory Magarshak
  • 1,883
  • 2
  • 25
  • 35
7

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

Hokascha
  • 1,709
  • 1
  • 23
  • 41
  • I had a similar issue. Waiting for the iframe to be ready before starting the player solve the issue. See @KMX's answer and also this https://stackoverflow.com/questions/50857499/youtube-api-error-failed-to-execute-postmessage-on-domwindow – NinjaFart Apr 08 '22 at 08:26
  • This works but it would impact page performance in case your iframe is not visible on the first fold of the page. – Deepanshu Batra Oct 11 '22 at 08:19
4

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

allo
  • 3,955
  • 8
  • 40
  • 71
ave
  • 41
  • 3
4

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"
                }, '*')
LukeSolar
  • 3,795
  • 4
  • 32
  • 39
4

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.

Mau
  • 1,257
  • 2
  • 15
  • 21
  • Thank you for that insight about it being chrome et al. BTW I notice when I scroll down page a bit so no video embed is showing, the error count stops for good (until page reloaded). Otherwise, on fresh page load the error counter continuously keeps producing error until browser becomes unresponsive (wordpress plugin producing this brought me here). – B. Shea Jun 17 '21 at 00:55
2

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

2

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 );
Terry Lin
  • 2,529
  • 22
  • 21
2

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.

KMX
  • 2,631
  • 1
  • 23
  • 28
  • Putting everything inside `document.addEventListener("DOMContentLoaded", function () {` unfortunately didn't help. – Ryan Aug 25 '19 at 19:04
2

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.

Roger Krueger
  • 283
  • 3
  • 8
  • It sure would appear I'm wasting my time worrying about this error when in fact the web site and the embedded vids are all working fine... a user of the web site wouldn't be worrying about this, maybe I won't either. – StackOverflowUser Dec 03 '21 at 00:10
1

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

T.Todua
  • 53,146
  • 19
  • 236
  • 237
1

This helped me (with Vue.js)

Found here vue-youtube

mounted() {
  window.YTConfig = {
    host: 'https://www.youtube.com/iframe_api'
  }
  const host = this.nocookie ? 'https://www.youtube-nocookie.com' : 'https://www.youtube.com'

  this.player = player(this.$el, {
    host,
    width: this.width,
    height: this.height,
    videoId: this.videoId,
    playerVars: this.playerVars
  })
  ...
}

UPDATE: Working like a charm like this:

...
youtube(
  video-id="your_video_code_here"
  nocookie
)
...
data() {
  return {
    playerVars: {
      origin: window.location.href,
    },
  };
},
Eugene
  • 85
  • 1
  • 9
1

Extending @Hokascha's answer above it was also lazy loading for me being automatically added by WordPress. This code will remove all lazy loading on the site's iframes (add to functions.php):

function disable_post_content_iframe_lazy_loading( $default, $tag_name, $context ) {
    if ( 'iframe' === $tag_name ) {
        return false;
    }
    return $default;
}
add_filter('wp_lazy_loading_enabled', 'disable_post_content_iframe_lazy_loading', 10, 3);
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
Shirls
  • 11
  • 1
0

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.

denns
  • 1,105
  • 1
  • 11
  • 24
  • Could you please see if you understand what I'm experiencing in YouTube here and whether it's related? https://stackoverflow.com/q/57649870/470749 Maybe you'll have an answer. Thanks! – Ryan Aug 25 '19 at 21:36
0

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.

Gavin
  • 7,544
  • 4
  • 52
  • 72
0

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.

TomSjogren
  • 769
  • 10
  • 20
0

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

0

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

0

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.

stvar
  • 6,551
  • 2
  • 13
  • 28
matan yemini
  • 141
  • 2
  • 4
0

I think we could customize the sendMessage of the YT.Player

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

I used this function to resolve in my project.

HoangHieu
  • 2,802
  • 3
  • 28
  • 44
  • What is `this.h.contentWindow` here. From where this comes in? Thanks! – GRD Sep 08 '22 at 14:09
  • @GRD that is the content of the function from YT.Player. you could find the function that named sendMessage on the youtube script. – HoangHieu Sep 09 '22 at 02:06
0

I got a similar error message in my attempt to embed a Stripe pricing table when:

  1. Adding the embed code via PHP through a custom WordPress short code

  2. Or by appending the code to the page dynamically with JavaScript (Even a using a setTimeout() delay to ensure the DOM was loaded didn't work).

I was able to solve this on my WordPress site by adding the code to the WordPress page itself using plain html code in the block editor.

enter image description here

Benson
  • 4,181
  • 2
  • 26
  • 44
0

I am using Google Chrome and had the same problem for a few days. Then, I realized that the error only occurred when I used a playlist attribute to force playback in a loop. Therefore, I deleted my playlist attribute and used the onStateChange method to restart playback. If you ever encounter this problem and have a playlist attribute, it's worth checking whether it is the cause.

Péah
  • 131
  • 1
  • 3
  • 11
0

I use The Angular Youtube component here and this is what they have said about this run time error: i.e. no solution yet.

I've seen this occasionally in our dev app as well, but I don't think that we can do much about it since it comes from YouTube's code that's isolated inside of the iframe.

Ref: https://github.com/angular/components/issues/22835#issuecomment-853176948

Sampath
  • 63,341
  • 64
  • 307
  • 441
-1

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.

-1

You can try :

document.getElementById('your_id_iframe').contentWindow.postMessage('your_message', 'your_domain_iframe')
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
HoaTruong
  • 1
  • 3
-1

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.