2

So I'm writing a TamperMonkey script that sends specific videos to YouTube's embedded player however I want to automatically send them back once the video is finished.

So for example, video http://youtube.com/watch?v=XXXXX it would redirect to http://youtube.com/v/XXXXX. And then, once the video is complete, it would use window.history.go(-2) (as -1 would go to the normal page causing a loop).

The problem I'm having is that I haven't been able to get the second part, the function that runs when the video finishes, to work.

I have tried following the api and looking at other peoples problems and seeing what helped them but I can't seem to get it.

At the moment this is the code I have.

$(document).ready( function() {

    var loc = document.location.href;
    var l = loc.split('/');
    var s = l[4];
    var id = s.split('?')[0]

    // create youtube player
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
            height: '100%',
            width: '100%',
            videoId: id,
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    // autoplay video
    function onPlayerReady(event) {
        event.target.playVideo();
        alert('spotted');
    }

    // when video ends
    function onPlayerStateChange(event) {        
        if(event.data === 0) {            
            window.history.go(-2);
        }
    } 
});

I would appreciate it if someone would work with me to get this script working. Thanks.

Spedwards
  • 4,167
  • 16
  • 49
  • 106
  • @RobW Unfortunately this didn't help my cause. As the default YouTube embed page has no head element, I cannot inject my scripts correctly. – Spedwards Jan 12 '14 at 05:17
  • @RobW Ok stupid question because I'm having a mental blank right now. How would I (using jQuery), inject the script, into the page. It's a TamperMonkey script so I have to keep it all together there. – Spedwards Jan 12 '14 at 10:38
  • Oh sorry, my bad. I didn't see the tampermonkey part. Now you're mentioning it, drop jQuery (you don't need it) and use the techniques described in this Q&A: http://stackoverflow.com/q/9515704. The question is about Chrome extensions / YouTube events, but the solution is conceptually equivalent to User scripts / YouTube events. – Rob W Jan 12 '14 at 10:42
  • @Spedwars I have deleted these two comments that wrongly assumed that you're writing the HTML yourself. My last comment is applicable in your case, please read it. – Rob W Jan 12 '14 at 10:52
  • @RobW I read it. I went around my problem a different way by removing the video frame on the video page and replacing it with the embed one. However thanks for the help :) – Spedwards Jan 12 '14 at 22:49

0 Answers0