title: Detect end of Youtube video inside the Youtube website in Javascript
body: <p>I want to detect the end of a Youtube video I am watching on the Youtube website with Javascript.</p>
  
  <p>I know they have an API for that, I tried to loaded it in the page with GreaseMonkey, but it doesn't seem to work. Maybe the API is only for embeded videos on other websites?</p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>if (window.location.href.indexOf("&amp;enablejsapi=1") == -1)
    {
      window.location = window.location.href + "&amp;enablejsapi=1";
    }
  
  var api = document.createElement('script');
  api.type = 'text/javascript';
  api.src = "https://www.youtube.com/iframe_api";
  document.body.appendChild(api);
  
  var onFinish = document.createElement('script');
  onFinish.type = 'text/javascript';
  var onFinishContent = "function onPlayerStateChange(event) { console.log('test'); if (event.data == YT.PlayerState.ENDED) { console.log('end'); } }"
  var textNode = document.createTextNode(onFinishContent);
  onFinish.appendChild(textNode);
  document.body.appendChild(onFinish);
  
  function onPlayerStateChange(event)
  {
    console.log("test");
    if (event.data == YT.PlayerState.ENDED)
      {
        console.log("end");
      }
  }
  </code></pre>
  
  <p>Like you can see, I tried to make the <code>onPlayerStateChange</code> function callable in two ways, one directly with Greasemonkey, and the second one by injecting a script node. Both of them doesn't work, I never see the "test" message I display in the console.</p>
  
  <p>Does anyone know why I can't seem to be able to load the API?</p>