Słuchanie zdarzenia Youtube w JavaScript lub jQuery

Mam suwak, który zawiera 4 filmy z youtube, które są osadzone za pomocą kodu embed iframe

http://www.youtube.com/embed/'.$i.'?enablejsapi=1

Próbuję sprawić, aby zdarzenie onStateChange dowolnego z czterech filmów wywołało funkcję, którą wywołałem stopCycle(), która zatrzyma suwak, gdy wideo zacznie się odtwarzać. Ramki iframes nie mają identyfikatora. Nie jestem pewien, jak prawidłowo uchwycić to wydarzenie i przydałaby mi się każda rada, co robię źle.

<script charset="utf-8" type="text/javascript" src="http://www.youtube.com/player_api"></script>

var playerObj = document.getElementById("tab2"); // the container for 1 of the 4 iframes

playerObj.addEventListener("onStateChange", "stopCycle");

function stopCycle(event) {
    alert('Stopped!');
}
Author: Rob W, 2011-11-03

4 answers

YouTube Frame API Czy obsługuje istniejące ramki. Aby poprawić wykorzystanie, stworzyłem kilka funkcji pomocniczych. Zobacz poniższy kod + komentarze oraz demo: http://jsfiddle.net/YzvXa/197

Aby powiązać funkcje z istniejącymi ramkami, musisz przekazać referencję ID do ramki. W Twoim przypadku ramka jest zawarta w kontenerze z id="tab2". Zdefiniowałem niestandardową funkcję dla łatwiejszego realizacja:

function getFrameID(id){
    var elem = document.getElementById(id);
    if (elem) {
        if(/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
        // else: Look for frame
        var elems = elem.getElementsByTagName("iframe");
        if (!elems.length) return null; //No iframe found, FAILURE
        for (var i=0; i<elems.length; i++) {
           if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
        }
        elem = elems[i]; //The only, or the best iFrame
        if (elem.id) return elem.id; //Existing ID, return it
        // else: Create a new ID
        do { //Keep postfixing `-frame` until the ID is unique
            id += "-frame";
        } while (document.getElementById(id));
        elem.id = id;
        return id;
    }
    // If no element, return null.
    return null;
}

// Define YT_ready function.
var YT_ready = (function() {
    var onReady_funcs = [], api_isReady = false;
    /* @param func function     Function to execute on ready
     * @param func Boolean      If true, all qeued functions are executed
     * @param b_before Boolean  If true, the func will added to the first
                                 position in the queue*/
    return function(func, b_before) {
        if (func === true) {
            api_isReady = true;
            while (onReady_funcs.length) {
                // Removes the first func from the array, and execute func
                onReady_funcs.shift()();
            }
        } else if (typeof func == "function") {
            if (api_isReady) func();
            else onReady_funcs[b_before?"unshift":"push"](func); 
        }
    }
})();
// This function will be called when the API is fully loaded
function onYouTubePlayerAPIReady() {YT_ready(true)}

// Load YouTube Frame API
(function() { // Closure, to not leak to the scope
  var s = document.createElement("script");
  s.src = (location.protocol == 'https:' ? 'https' : 'http') + "://www.youtube.com/player_api";
  var before = document.getElementsByTagName("script")[0];
  before.parentNode.insertBefore(s, before);
})();

// wcześniej zdefiniowano podstawowe funkcje. Zapraszamy do zapoznania się z realizacją:

var player; //Define a player object, to enable later function calls, without
            // having to create a new class instance again.

// Add function to execute when the API is ready
YT_ready(function(){
    var frameID = getFrameID("tabs2");
    if (frameID) { //If the frame exists
        player = new YT.Player(frameID, {
            events: {
                "onStateChange": stopCycle
            }
        });
    }
});

// Example: function stopCycle, bound to onStateChange
function stopCycle(event) {
    alert("onStateChange has fired!\nNew state:" + event.data);
}

Jeśli chcesz wywołać dodatkowe funkcje w późniejszym momencie, np. wyciszyć wideo, użyj:

player.mute();
  • jeśli wystarczy wywołać proste funkcje jednokierunkowe , nie jest konieczne używanie tego kodu. Zamiast tego użyj funkcji callPlayer zdefiniowanej w ta odpowiedź.
  • jeśli chcesz zaimplementować tę funkcję dla wiele klatek, jednocześnie, spójrz na ta odpowiedź. zawiera również szczegółowe wyjaśnienie getFrameID i YT_ready.
 40
Author: Rob W,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:02

Możesz użyć wtyczki tubeplayer, która zawiera wiele wydarzeń do wysłuchania.

 1
Author: topek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-02 23:23:08

Od wczoraj to już nie działa. Zmiana stanu nie jest zwolniona. Jeffrey opublikował szybką poprawkę, ale nie jestem w stanie zaktualizować powyższej odpowiedzi

Więcej informacji o tym numerze https://code.google.com/p/gdata-issues/issues/detail?id=4706

Działa: -) z fixem

Dodaj następującą funkcję

function onReady() {
    player.addEventListener('onStateChange', function(e) {
        console.log('State is:', e.data);
    });
}

I przed "onStateChange": stopCycle dodaj "onReady": onReady,

 1
Author: ceasar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-13 12:36:27

Mam tę funkcję na czacie, która umożliwia użytkownikom publikowanie filmów z youtube. Adres URL vid jest dołączony jako źródło istniejącego iframe z id.

To co zauważyłem to-chociaż ?enablejsapi = 1 jest dodawane - że skrypt działa tylko daleko istniejących iframes na pageload.

Jak można to zrobić, gdy chce ten skrypt do bindowania po ustawieniu nowego źródła dla iframe?

 0
Author: ingridsede,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-30 10:35:00