Youtube Javascript API: not working in IE

2019-08-12 07:20发布

问题:

I have an embedded Youtube video, and I want to capture events when the user pauses the video, skips around, etc. Following the examples at Google's documentation (http://developers.google.com/youtube/js_api_reference), I do the following:

var video = (my video ID here);
var params = { allowScriptAccess: "always" };
var atts = { id: "youtubeplayer" };
var x = 854;
var y = 480;
swfobject.embedSWF("http://www.youtube.com/v/" + video + "?enablejsapi=1&playerapiid=ytplayer&version=3", "bobina", x, y, "8", null, null, params, atts);

function onYouTubePlayerReady(playerId) {
      youtubeplayer = document.getElementById('youtubeplayer');
      youtubeplayer.addEventListener("onStateChange", "onytplayerStateChange");
      youtubeplayer.setPlaybackQuality('large');
      }

function onytplayerStateChange(newState) {
    //Make it autoplay on page load
    if (newState == -1) {
        youtubeplayer.playVideo();
        }

    var tiempo=youtubeplayer.getCurrentTime();
    //Rounds to 2 decimals
    var tiempo = Math.round(tiempo*100)/100;
    alert(tiempo);
    }

Now, all this works perfectly in Firefox and Safari, but there's no way to make it work in IE8 (by which I mean: the video loads, but events aren't captured: the event handler never gets called). According to javascript addEventListener onStateChange not working in IE , IE doesn't support addEventListener(), so I tried replacing that line with:

youtubeplayer.attachEvent("onStateChange", onytplayerStateChange);

But it doesn't work either. (The author of that question says that he finally solved it by putting "onComplete in my colorbox and put the swfobject in that", but I'm not using a colorbox here (I don't even know what that is), so I don't understand what he means.

Using alerts() to debug, I see that the first function (onYoutubePlayerReady()) is indeed called, but I can't even tell whether the event listener isn't being registered or whether it's the getElementById() that isn't working; I tried debugging by adding a:

alert(typeof youtubeplayer);

Right after it, but it doesn't even pop up.

Oh, and one more thing: the video starts automatically in Firefox and Safari, but in IE it doesn't either. (And yes, I'm running this on a server, not on a local page).

Anyone has any ideas? I don't really know what else to try.

回答1:

Okay, found the solution. Guess what it was? Just write is as:

var youtubeplayer = document.getElementById('youtubeplayer');

And it works perfectly in IE 8. All it needed was the "var" keyword.

Just in case it's useful for someone else with the same problem...