Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6591385
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T17:25:01+00:00 2026-05-25T17:25:01+00:00

I want to be able to control iframe based YouTube players. This players will

  • 0

I want to be able to control iframe based YouTube players. This players will be already in the HTML, but I want to control them via the JavaScript API.

I’ve been reading the documentation for the iframe API which explain how to add a new video to the page with the API, and then control it with the YouTube player functions:

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('container', {
        height: '390',
        width: '640',
        videoId: 'u1zgFlCw8Aw',
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

That code creates a new player object and assigns it to ‘player’, then inserts it inside the #container div. Then I can operate on ‘player’ and call playVideo(), pauseVideo(), etc. on it.

But I want to be able to operate on iframe players which are already on the page.

I could do this very easily with the old embed method, with something like:

player = getElementById('whateverID');
player.playVideo();

But this doesn’t work with the new iframes. How can I assign a iframe object already on the page and then use the API functions on it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T17:25:01+00:00Added an answer on May 25, 2026 at 5:25 pm

    Fiddle Links: Source code – Preview – Small version
    Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

    As a result of a deep code analysis, I’ve created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

    On 17 may 2012, the code size was doubled in order to take care of the player’s ready state. If you need a compact function which does not deal with the player’s ready state, see http://jsfiddle.net/8R5y6/.

    /**
     * @author       Rob W <gwnRob@gmail.com>
     * @website      https://stackoverflow.com/a/7513356/938089
     * @version      20190409
     * @description  Executes function on a framed YouTube video (see website link)
     *               For a full list of possible functions, see:
     *               https://developers.google.com/youtube/js_api_reference
     * @param String frame_id The id of (the div containing) the frame
     * @param String func     Desired function to call, eg. "playVideo"
     *        (Function)      Function to call when the player is ready.
     * @param Array  args     (optional) List of arguments to pass to function func*/
    function callPlayer(frame_id, func, args) {
        if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
        var iframe = document.getElementById(frame_id);
        if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
            iframe = iframe.getElementsByTagName('iframe')[0];
        }
    
        // When the player is not ready yet, add the event to a queue
        // Each frame_id is associated with an own queue.
        // Each queue has three possible states:
        //  undefined = uninitialised / array = queue / .ready=true = ready
        if (!callPlayer.queue) callPlayer.queue = {};
        var queue = callPlayer.queue[frame_id],
            domReady = document.readyState == 'complete';
    
        if (domReady && !iframe) {
            // DOM is ready and iframe does not exist. Log a message
            window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
            if (queue) clearInterval(queue.poller);
        } else if (func === 'listening') {
            // Sending the "listener" message to the frame, to request status updates
            if (iframe && iframe.contentWindow) {
                func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
                iframe.contentWindow.postMessage(func, '*');
            }
        } else if ((!queue || !queue.ready) && (
                   !domReady ||
                   iframe && !iframe.contentWindow ||
                   typeof func === 'function')) {
            if (!queue) queue = callPlayer.queue[frame_id] = [];
            queue.push([func, args]);
            if (!('poller' in queue)) {
                // keep polling until the document and frame is ready
                queue.poller = setInterval(function() {
                    callPlayer(frame_id, 'listening');
                }, 250);
                // Add a global "message" event listener, to catch status updates:
                messageEvent(1, function runOnceReady(e) {
                    if (!iframe) {
                        iframe = document.getElementById(frame_id);
                        if (!iframe) return;
                        if (iframe.tagName.toUpperCase() != 'IFRAME') {
                            iframe = iframe.getElementsByTagName('iframe')[0];
                            if (!iframe) return;
                        }
                    }
                    if (e.source === iframe.contentWindow) {
                        // Assume that the player is ready if we receive a
                        // message from the iframe
                        clearInterval(queue.poller);
                        queue.ready = true;
                        messageEvent(0, runOnceReady);
                        // .. and release the queue:
                        while (tmp = queue.shift()) {
                            callPlayer(frame_id, tmp[0], tmp[1]);
                        }
                    }
                }, false);
            }
        } else if (iframe && iframe.contentWindow) {
            // When a function is supplied, just call it (like "onYouTubePlayerReady")
            if (func.call) return func();
            // Frame exists, send message
            iframe.contentWindow.postMessage(JSON.stringify({
                "event": "command",
                "func": func,
                "args": args || [],
                "id": frame_id
            }), "*");
        }
        /* IE8 does not support addEventListener... */
        function messageEvent(add, listener) {
            var w3 = add ? window.addEventListener : window.removeEventListener;
            w3 ?
                w3('message', listener, !1)
            :
                (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
        }
    }
    

    Usage:

    callPlayer("whateverID", function() {
        // This function runs once the player is ready ("onYouTubePlayerReady")
        callPlayer("whateverID", "playVideo");
    });
    // When the player is not ready yet, the function will be queued.
    // When the iframe cannot be found, a message is logged in the console.
    callPlayer("whateverID", "playVideo");
    

    Possible questions (& answers):

    Q: It doesn’t work!
    A: “Doesn’t work” is not a clear description. Do you get any error messages? Please show the relevant code.

    Q: playVideo does not play the video.
    A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

    Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn’t execute any function!
    A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

    Q: I get error message “An invalid or illegal string was specified”. Why?
    A: The API doesn’t function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

    Q: How did you know this?
    A: I have spent some time to manually interpret the API’s source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

    Q: What browsers are supported?
    A: Every browser which supports JSON and postMessage.

    • IE 8+
    • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
    • Opera 10.50+
    • Safari 4+
    • Chrome 3+

    Related answer / implementation: Fade-in a framed video using jQuery
    Full API support: Listening for Youtube Event in jQuery
    Official API: https://developers.google.com/youtube/iframe_api_reference

    Revision history

    • 17 may 2012
      Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
      Functions are automatically queued when the player is not ready yet.
    • 24 july 2012
      Updated and successully tested in the supported browsers (look ahead).
    • 10 october 2013
      When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can’t know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
    • 12 Dec 2013, recommended to add &origin=* in the URL.
    • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
    • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In vb.net (2008), I want to be able to control when a contextMenuStrip (context
I want to control the mouse pointer with my application and be able to
I want to be able to invoke an SSIS package at will from a
I am programming a side-scrolling game. I want to be able to control the
I want to be able to control certain functions when a button is clicked
I want to be able to control which activities the user can press the
I want to be able to do something like this: <uc:MyUC> <CustomContent> <span id=name>johnny
I want to be able to control a DSLR camera to start/stop recording video.
I'm making an iOS game, and I want to be able to control the
I'm using LaTeX and BibTeX for an article, and I want to able to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.