I’m building a chrome extension to work with youtube’s API. This is how it works:
A content script is automatically injected on every youtube page via manifest.json
"permissions": ["tabs", "http://*/*", "https://*/*", "<all_url>", "background"],
"content_scripts": [
{
"matches": ["http://www.youtube.com/*"],
"js": ["inject.js"]
}
]
I have a lot of debugging points so I know the content script and listen.js gets loaded on every page.
With the content script I inject an extra piece of javascript code to listen to the player state. If the player state changes (paused, playing, ended, …) it gets logged in the console.
// inject listen.js into current webpage
var s = document.createElement('script');
s.src = chrome.extension.getURL("listen.js");
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
Then, in listen.js I listen to youtube’s player state.
var currentVideo = document.getElementById("movie_player");
currentVideo.addEventListener("onStateChange", "onytplayerStateChange");
function onytplayerStateChange() {
console.log("state changed");
};
The only problem is that I can’t get it to work consistently. Some Youtube pages give feedback on the player state, others don’t. There’s also no returning pattern. A youtube page that worked before could fail another time. Only if I reload the extension and open a youtube video in a new window, the player state gets logged in the console.
On the failing youtube pages the eventlistener in listen.js doesn’t seem to be active. If i try to log the playerstate in the console this error shows up:
#<HTMLEmbedElement> has no method 'getPlayerState'
Any idea why I can’t get consistent results? Is there something wrong with my permissions?
It seems like the method “getPlayerState” was not firing because the video was not loaded yet.
To fix it, you just have to put the addEventListener inside a function called “onYouTubePlayerReady(playerID)” which is part of the YouTube javascript API.