47
votes

I have an embedded YouTube video in one page and have a slider with which I can set the player speed.

I am using player.setPlaybackRate(value);

The problem is that I want ranges from 0.5 to 3, but the player API restricts the values only to predefined [0.25, 0.5, 1, 1.25, 1.5, 2].

In YouTube I can easily adjust the speed with document.getElementsByTagName("video")[0].playbackRate = 3 but on the iframe I do not have such access.

4

4 Answers

17
votes

Where do you see that the player API restricts the values? In the javascript API, you can use setPlaybackRate to set the suggested playback rate, but it says there is no guarentee that what you send will be set. You should use getAvailablePlaybackRates to get the list of playback rates and then choose an appropriate one. You can figure out what rate it was actually set to by listening to the onPlaybackRateChangeevent. If you try to set it to 3 and that is not one of the available rates, it will round towards 1 to the closest rate.

12
votes

EDIT: This doesn't work anymore.

This is due to the same-origin policy. When an iframe gets accessed by the root origin (your website) it seems to also change the origin of the iframe. So the video can't load from a different origin (youtube.com). See my test on JSFiddle.

I think the fact, that it worked before was a XSS security issue which has been fixed recently. So I can't imagine modifying something in the youtube iframe is even possible anymore. At least not in this way.

Thanks @maxple for pointing out!


Original post:

This should be possible with newer Browsers and the HTML5 Iframe Sandbox Attribute:

With the option you can access the iframe DOM node.

<iframe id="myframe" sandbox="allow-scripts" src="about:blank">    </iframe>

<script>
    var frame = document.getElementById("myframe");
    var fdoc = frame.contentDocument;

    fdoc.getElementsByTagName("video")[0].playbackRate = 3; // or whatever
</script>

See this post for more info.

7
votes

You can't do the same thing within an iFrame.

What you do within Youtube is to edit the actual video tag, but the only way to do so from another website is through the API provided by Google (due to XSS concerns), and if they've decided to only allow the proposed values, your best shot outside of doing something that may break their Terms of Service, is to contact Google and ask them to allow the third level of speed through the API.

3
votes

unfortunately, you are trying to edit content of iframe from another domain. none of major browsers allow you to do this via javascript.

i tried and created php file which would get contents of the youtube embed iframe

<?php 
    $url = $_GET['url'];
    $contents = file_get_contents($url);
    echo $contents;
?>

but somehow youtube blocks different origins and it gave me only black screen. as i guessed it is because youtube uses flash player for embed videos (instead of html5 as they do on website).

so i'm sorry but it is impossible.