Failed to execute 'postMessage' on 'DOMWindow': target/origin mismatch http vs https - target

I apologize up front as I'm very confused by my problem. I'm really in a bind because this is causing a problem on my production site.
I have a javascript player on my site which plays through song lists which can be hosted on youtube, soundcloud or vimeo. Yesterday I noticed this error which generally arises anytime you try to load a new song through "skipping" with the player buttons. This error just started in the last day or two. I am not seeing anything new in the youtube api release notes and this error occurs using Chrome, Firefox and Safari, so it is most likely not related to a change in the browser. Something that I am using has changed though, as I have not pushed new code in 18 days.
An example playlist is here: http://www.muusical.com/playlists/programming-music
I think I have isolated the way to reproduce the error, here are the steps:
Play a youtube hosted song.
Skip to any other song in the list (whether by pressing the skip buttons or directly pressing the play button on the song's row item).
*Note, that if the first song in the playlist is a youtube song, simply skipping to another song even without playing the initially loaded youtube song will produce the error.
Essentially, the error seems to occur once you have loaded and/or played a youtube song and attempt to skip to another song.
Let me know if you find an exception to this behavior.
I see this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.muusical.com') does not match the recipient window's origin ('http://www.muusical.com').
I load the player with using the youtube javascript api:
new YT.Player('playlist-player', {
playerVars: { 'autoplay': 1, 'fs': 0 },
videoId: "gJ6APKIjFQY",
events: {
'onReady': #initPlayerControls,
'onStateChange': #onPlayerStateChange
}
})
Which produces this iframe:
<iframe id="playlist-player" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="360" src="https://www.youtube.com/embed/gJ6APKIjFQY?autoplay=1&enablejsapi=1&origin=http%3A%2F%2Fwww.muusical.com"></iframe>
After hitting skip from the above youtube song, this is what I see loaded in the iframe:
<iframe id="playlist-player" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="360" src=""></iframe>
I support youtube, soundcloud and vimeo songs. It seems like once a youtube song is loaded the "origin" changes from http to https. I don't think it is necessary to include the embedding methods for the other hosts as this error occurs even if the entire playlist is only youtube and it does not occur in a playlist which consists of only songs from soundcloud and vimeo.
Also, this is how I am loading the youtube javascript:
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
Please let me know if you need me to clarify anything and thanks in advance for taking a look.

I have read a bit about this, some SO posts here and there and this link too : https://code.google.com/p/gdata-issues/issues/detail?id=5788
I was about to add a comment to your question, saying I was getting crazy over this ... but when I started to describe my setup, I found a way to avoid the issue ^^.
I start with an empty div element, and use the Youtube Iframe API to turn it into an iframe with all the necessary options.
I have multiple divs like this one, and usually use the same JS variable to store all those players, but one at a time (one replaces the other, and so on ... - it could be better, I know).
To fix the issue, I had the idea to destroy the player with youtubePlayer.destroy(); before building a new one from another element. No more JS errors bleeding in my Chrome console :).
Hope it helps, all the litterature I could read about http and https did not apply to my case, because I am not setting the iframe URL myself, and my website happens to be not https ...
I did restore an async call instead of a static script tag in my HTML but I do not think this was necessary.
EDIT : this error message is quite misleading in fact, it only vaguely means : you are not using the youtube API the proper way :)

#sodawillow's answer is partially correct but I'd like to give the details to the solution and what caused my code to stop calling the .destroy() method to remove the youtube player.
My site has a player which swaps out songs from various sites, one of them being Youtube. There can be different methods for removing a player depending on the type it is. My code checks for the existence of a youtube player and if passes the check then it uses the .destroy() method which only the youtube player has. The problem is that YouTube changed the names of some of the static variables on their player object. For example, if I created a player via:
var player = new YT.Player('playlist-player', {
playerVars: { 'autoplay': 1, 'fs': 0 },
videoId: "gJ6APKIjFQY",
events: {
}
})
then there would be a variable player.L which held the string "player". So to check if the current player was a YouTube player and remove it I did this:
if (player.L == "player") {
player.destroy();
} else {
//handle the removal of the Soundcloud or Vimeo player.
}
Sometime recently Youtube changed the location of the string "player" to now reside at player.M. I could change the above code to check player.M instead of player.L and that would work but to try to avoid this issue in the future I instead have implemented:
if (player.destroy) {
player.destroy();
} else {
//handle the removal of the Soundcloud or Vimeo player.
}
As long as Youtube does not remove the .destroy() method unannounced this will not cause any issues.
So in summary, the issue was as #sodawillow guessed, I was not using the .destroy() method to remove the Youtube player. The reason was because Youtube made some unannounced changes to their api, changing the location of some of the static variables.

This error belongs to the Google Youtube API.
Inside "https://www.youtube.com/iframe_api":
if (!window['YT']) {
var YT = {loading: 0, loaded: 0};
}
if (!window['YTConfig']) {
var YTConfig = {'host': 'http://www.youtube.com'};
}
They use http instead of https.
We need to override the 'host' option and 'widget_referrer' same as 'origin'.
player = new YT.Player('player', {
host: 'https://www.youtube.com',
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
...
origin: "https://www.enziin.com",
widget_referrer: "https://www.enziin.com"
}
Goodluck.

My solution is to write all the Youtube player logic in a separate page (as blank as posible) , and that page be referenced in an IFRAME tag.
<iframe src="/youtube_frame/?data=SOME_DATA -%>" height="400px" width="100%" frameborder="0" border="0" scrolling="no"></iframe>
Then, your youtube_frame.html will be something like this:
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
// event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
console.log("OnplayerStateChange");
if (event.data == YT.PlayerState.PLAYING && !done) {
console.log("OnplayerStateChange - If statement");
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
(As a marginal note: my context is that Prototype.js interferes with the event 'OnStateChange', and we cannot remove this dependency.
Using a jsfiddle would not be useful to reproduce the issue, as it has few dependencies.
My app here is built in Rails, and using this plugin for showing a Video playlist: https://github.com/Giorgio003/Youtube-TV/)

Related

Youtube Closed Caption for HTML5 Not Working

I am having issues displaying closed caption on youtube videos using the iframe player.
Here's the code I am using:
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
event.target.loadModule('captions');
}
</script>
</body>
</html>
Here's a gist https://gist.github.com/khirakawa/0a81b3039a85b9875b59
This is basically the same sample code that's on the API reference page, https://developers.google.com/youtube/iframe_api_reference. I call event.target.loadModule('captions'); on a player state change event.
I could not find any documentation on their API reference page about loading caption modules, but I did find the code to load the caption module in this ticket https://code.google.com/p/gdata-issues/issues/detail?id=444
I tried this on both Safari and Chrome with no luck.
The local storage values I see when youtube is opened is:
yt-remote-connected-devices {"data":"[]","expiration":1412291704974,"creation":1412205304974}
yt-remote-device-id {"data":"27238aac-9452-4ae8-9b9f-1e29278e4d3b","expiration":1443741293991,"creation":1412205293992}
yt-remote-load-account-screens {"data":"false","expiration":1443741304972,"creation":1412205304972}
yt-remote-online-screens {"data":"[]","expiration":1412205364973,"creation":1412205304973}
Notice that its missing entries for captions (I can't recall what the key values were, but I know there were two of them. One to enable captions and the other for caption settings).
The demo page (https://developers.google.com/youtube/youtube_player_demo) shows closed captions if you check cc_load_policy, but that's only an AS3 option.
This was working on October 6th, but I cannot get it to work anymore. I'm not sure if the youtube script itself changed.
I tried moving event.target.loadModule('captions'); to the onPlayerReady handler, but that didn't work either.
Any help would be greatly appreciated.
I was able to load captions by setting cc_load_policy to 1. I also realized that the sample video on the youtube site defaulting to using <embed> (read: Flash), instead of using the html5 video player.
I am not certain when the iframe player decides to use over , but I did find a video that does use the html5 video tag. Even so, I had to set cc_load_policy to 1 in order for it to work. Neither loadModule nor unloadModule works anymore.
I hope this helps anyone else who ran into this issue.

Google drive embed NO iframe

Is there any way to embed google drive video without using iframes?
Just like you can do with youtube video:
<object width="320" height="180">
<param name="movie" value="http://www.youtube.com/v/UHk6wFNDA5s&showinfo=0">
<param name="wmode" value="transparent">
<embed src="http://www.youtube.com/v/UHk6wFNDA5s&showinfo=0" type="application/x-shockwave-flash" wmode="transparent" width="320" height="180">
</object>
The suggested embed code from google docs (using iframe) is:
<iframe src="https://docs.google.com/file/d/0B7CQ5XvLuIGrQlJUNUhpQVltZ0U/preview" width="640" height="385"></iframe>
It's possible but not officially supported.
After some study of the result generated by the iframe embed from Google Drive and the iframe from YouTube I've digged into the YouTube JS Player API and found out that it's possible using SWFObject embed
Here is the code that I use to add the player object:
function YT_createPlayer(divId, videoId) {
var params = {
allowScriptAccess: "always"
};
var atts = {
id: videoId
};
//Build the player URL SIMILAR to the one specified by the YouTube JS Player API
var videoURL = '';
videoURL += 'https://video.google.com/get_player?wmode=opaque&ps=docs&partnerid=30'; //Basic URL to the Player
videoURL += '&docid=' + videoId; //Specify the fileID ofthe file to show
videoURL += '&enablejsapi=1'; //Enable Youtube Js API to interact with the video editor
videoURL += '&playerapiid=' + videoId; //Give the video player the same name as the video for future reference
videoURL += '&cc_load_policy=0'; //No caption on this video (not supported for Google Drive Videos)
swfobject.embedSWF(videoURL,divId, widthVideo, heightVideo, "8", null, null, null, null);
}
You need to fetch the fileId from Google Drive some how (JS or server side, you can use a GAS Servlet if you want to host the site on Google Drive).
Most of the YouTube Player Parameters works, and events to control the playing status from JS are fired; so basically anything from the Youtube Documentation works.
Do you mean like this:
<object width="420" height="315" data="https://docs.google.com/file/d/0B7CQ5XvLuIGrQlJUNUhpQVltZ0U/preview">
<embed width="420" height="315" src="https://docs.google.com/file/d/0B7CQ5XvLuIGrQlJUNUhpQVltZ0U/preview">
I have tested the code and it works.
I used the example code from W3Schools, but cannot paste the code here as it is their copyright, just follow the link to see it.
The second part is to get the link to the images correct. I found using the link directly from Drive didn't work, so I created a new page in my site and added all the images I wanted. I disabled the page from navigation so it wouldn't be found unless they use search. After publishing, I opened the page and used Inspect on the browser to find the tag for each image. I then copied the element which looked like this.
<img src="https://lh3.googleusercontent.com/qt ... 4jM=w1175" class="CENy8b" role="img" style="width: 100%; margin: 0%">
I added the title attribute to this, so it is possible to see which images are included. I also removed the class="CENy8b" attribute as it doesn't seem to be required.
<img src="https://lh3.googleusercontent.com/qt ... 4jM=w1175" role="img" style="width: 100%; margin: 0%" title = "image 1">
I then pasted this over the tag in the code from W3Schools, repeating for each of the images. The W3Schools code has a where they have dots under the images to show which image from the set is being displayed. The number of dots needs to match the number of images.
Having done all the above I copied the code from the editor and used Embed code on Sites to paste it in. You can see the images ticking over in the Sites editor and after publishing it works fine on the live page.
The W3Schools code uses a 2 s delay between images. It is fairly easy to find where this is set in the code to change it to an appropriate value for your site.

Initializing an empty player with Youtube Javascript API

I have made a component for my web app that initializes a YouTube player on the page. This player will be used to an un-demand video on to the page. However, when initializing the player, I have to pass a video for it to initialize:
//javascript
swfobject.embedSWF( makeUrl( 'http://www.youtube.com/v/NINOxRxze9k', {
version : 3,//youtube api version
autoplay : 0,//automatically start playing
color : 'white',//color for the 'viewed' part of the video
autohide : 0,//automatically hide the controls
controls : 0,//don't show the controls
disablekb : 1,//disable keyboard shortcuts
enablejsapi : 1,//enable javascript api
fs : 0,//disable full-screen
playerapiid : id,//player api id that is used for javascript api
//playlist : videoIds.join( ',' ),//the list of video ids to play (it can be only one item)
showinfo : 0,//don't show video information like title
rel : 0,//don't show related videos after playback is finished
theme : 'light',//use the light theme (the other one is 'dark')
showsearch : 0, //don't show the search bar (it's disabled when 'rel' is 0)
origin : window.location.hostname//it is a security thing necessary for enabling javascript api
}), id, '300', '200', '8', null, null, params, atts);
(notice the 'NINOxRxze9k' part on the first line).
The question is: how can I initialize a YouTube player without initializing it for a specific video? I don't want it to show a snapshot of the video ready to be played. I want it to be blank before I start playing anything on it.
Sitenote: as you can see from Google's documentation, the VIDEO_ID is passed to embedSWF(). I tried removing it but it stopped working.
I think that this is the answer to the same question, but if you use the Player IFrame API:
Init YouTube iframe player without video ID
Not sure if this will help but here it is anyway.
I have played with YT-api for a while in flash and web for different projects and found it to be a LARG system that takes a lot of reading.
The only time I have found it to have a blank player loaded was in a flash app. Also it needed to be chromeles.
I did an "amature" tutorial with download for people here.
http://www.youtubetutsite.com/player.php?videoID=kO_WVIYdLDc
Only sugesting as you are using the SWF player in your app.

Popcorn JS - Use of popcorn with Youtube on an iPad or iOS device

I am using popcornjs to load an interact with a video from youtube.
When I use the code from the documentation:
<html>
<head>
<script src="http://popcornjs.org/code/dist/popcorn-complete.min.js"></script>
<script>
// ensure the web page (DOM) has loaded
document.addEventListener("DOMContentLoaded", function () {
// Create a popcorn instance by calling the Youtube player plugin
var example = Popcorn.youtube(
'#video',
'http://www.youtube.com/watch?v=CxvgCLgwdNk' );
// add a footnote at 2 seconds, and remove it at 6 seconds
example.footnote({
start: 2,
end: 6,
text: "Pop!",
target: "footnotediv"
});
// play the video right away
//example.play(); => commented because you can't autoplay on ios
}, false);
</script>
</head>
<body>
<div id="video" style="width: 360px; height: 300px;" ></div>
<div id="footnotediv"></div>
</body>
</html>
It looks perfect on any browser, but nothing shows on the iPad.
When I load a video with popcorn but without using Youtube, it seems to work fine.
What can I do?
Unfortunately, the ipad doesn't support Flash. We do have a ticket in progress with Popcorn to switch to their HTML5 API, which you can view here:
https://webmademovies.lighthouseapp.com/projects/63272/tickets/329-support-youtube-html5-api-playback-engine
Hope that helps,
Brett
Try using the smart media wrapper:
var example = Popcorn.smart(
'#video',
'http://www.youtube.com/watch?v=CxvgCLgwdNk' );
// add a footnote at 2 seconds, and remove it at 6 seconds
example.footnote({
start: 2,
end: 6,
text: "Pop!",
target: "footnotediv"
});
// play the video right away
//example.play(); => commented because you can't autoplay on ios
}, false);
I too am facing the issue, Youtube Popcorn is not working in iPad. But interestingly I found a site using popcorn youtube and it works fine in iPad
Link:
http://www.retn.org/show/south-burlington-school-board-meeting-october-2-2013
So, I guess someone should come up with more specific answer
Edit this file in your code:
https://github.com/mozilla/popcorn-js/blob/master/wrappers/youtube/popcorn.HTMLYouTubeVideoElement.js
Comment body part of onPlayerReady() on line no 117 and add following statements in this function in case of iPad.
addYouTubeEvent("play", onFirstPlay);
playerReady = true;
mediaReady = true;
player.mute();
Reason: Youtube on iPad wants user interaction, you can't start it programmatically and due to player.isMuted() method returns false in case of iPad, addYouTubeEvent("play", onFirstPlay) statement is never called.

iPad HTML5 Audio Tracks Not Resetting

For some odd reason the HTML5 Audio API won't give me access to currentTime in iOS 4 and 5 for iPads and iPods. I need to adjust currentTime whenever an audio element is played, but it acts like the current time isn't accessible. Looked everywhere for an answer on this and I can't figure it out. My code below works fine in all modern browsers, so I'm a bit stumped.
My HTML markup
<p>
<a class="audio" href="assets/audio/ambient-sounds-1.mp3" data-flash="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/niftyplayer.swf" data-mp3="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/ambient-sounds-1.mp3" data-ogg="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/ambient-sounds-1.ogg">
Ambient Sounds
<span class="audio-play">Play</span>
<audio preload="">
<source preload="" src="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/ambient-sounds-1.mp3" type="audio/mpeg">
<source preload="" src="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/ambient-sounds-1.ogg" type="audio/ogg">
</audio>
</a>
</p>
<p>
<a class="audio" href="assets/audio/city_street.mp3" data-flash="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/niftyplayer.swf" data-mp3="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/city_street.mp3" data-ogg="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/city_street.ogg">
City Street Sounds
<span class="audio-play">Play</span>
<audio preload="">
<source preload="" src="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/city_street.mp3" type="audio/mpeg">
<source preload="" src="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/city_street.ogg" type="audio/ogg">
</audio>
</a>
</p>
<p>
<a class="audio" href="#" data-flash="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/niftyplayer.swf" data-mp3="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/crash.mp3" data-ogg="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/crash.ogg">
Loud Crash
<span class="audio-play">Play</span>
<audio preload="">
<source preload="" src="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/crash.mp3" type="audio/mpeg">
<source preload="" src="http://athens.sierrabravo.net/~ablue/plato/videoplayer/assets/audio/crash.ogg" type="audio/ogg">
</audio>
</a>
</p>
My JavaScript
AudioPlayer = {
init: function () {
var player = this;
this.audio = $('.audio'); // Save and cache all audio elements so they can be targeted by mass stop()
player.audio.each( function() {
// Bind each audio element
player.bind($(this));
});
},
bind: function (object) {
var player = this;
object.bind('touchstart click', function() {
// get the real DOM element, not the jQuery array
var audio = $(this).find('audio').get(0);
if(audio.paused) { // Check if its playing
player.play(audio);
}
else {
player.stop(audio);
}
return false;
});
},
play: function(audio) {
// Stop all existing audio elements and set them to 0
this.audio.each( function() {
var audioOther = $(this).find('audio').get(0);
audioOther.pause();
});
// Play the audio element
if(audio.currentTime) audio.currentTime = 0;
audio.play();
},
stop: function(audio) {
if(audio.currentTime) audio.currentTime = 0;
audio.play();
}
};
There is an answer as to why my code doesn't work, iOS 4 and 5 need the entire audio element to be completely destroyed (terrible solution, but it works). Here is a quick rundown on how to fix my issue if you've run into it.
Insert only 1 element into the page (I inserted mine right before the closing tag).
On click to play a new audio element, completely destroy the existing and rebuild it from scratch with the new track you want to play.
Call .play on the audio element and you'll be good to go.
I also have the same problem and googled then found this page and the below page
http://remysharp.com/2010/12/23/audio-sprites/
this guy probably found the more detailed answer.
I had these types of problems, and I too started using that desperate way to solve the issue which consists of recreating the audio component, reloading the source, etcetera.
A day or two ago I found that the source of the media content must be "pure" to be able to use it successfully from the ipad.
I want to express with "pure" all content that is not being "transmuted" by previous code that could change or delete it's metadata before it reaches the ipad client.
In the current project I am working on, I found that with Ipad I could not replay nor traverse to mm:ss any content located in the "documents" folder, but if I got that file and moved elsewhere, it worked perfectly, I could replay it on my ipad, go to the minute:second I wished, etcetera.
In my case, an .htaccess was forcing my apache server to send the "get" query through a "download.php" which was checking permissions and doing weird stuff of the like, and then this download.php was dispatching the file to the client, but not in a good way or a way more of the ipad's liking.
I removed the .htaccess bindings and the ipad got a nice audio handling again. (That download.php was of not too much good use anyway...)

Resources