最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - YouTube video not closing after it finishes playing - Stack Overflow

programmeradmin5浏览0评论

I'm currently loading a YouTube video inside a -UIwebView, this is working perfectly and the video starts playing automatically. but the problem is that once the video finishes inside the -UIwebViewit just stops and shows the play button. I would however want the video player to close so the users wouldn't have to manually hit the "Done" button every time.

Image of the screen when the video doesn't close.

Here's the link I launch the video inside the -UIwebview

NSString *youTubeVideoHTML = [NSString stringWithFormat:@"<!DOCTYPE html><html><head>
<style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script>

    var tag = document.createElement('script'); tag.src = \"\";
    var firstScriptTag = document.getElementsByTagName('script')[0]; 
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var player;

    function onYouTubePlayerAPIReady() { 
        player = new YT.Player('player', { 
            width:'320',
            height:'200',
            videoId:'%@',
            events: {
                'onReady': onPlayerReady,
            }
        });
    }

    function onPlayerReady(event) { 
        event.target.playVideo();
    }

</script> </body> </html>", [[NSUserDefaults standardUserDefaults]
objectForKey:@"detailVideoURL"]];

EDIT:

I tried implementing the first answer into my code and this is how it ended up like. I'm still unsure what I should add into the callback ?

NSString *youTubeVideoHTML = [NSString stringWithFormat:@"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script>
var tag = document.createElement('script'); tag.src = \"\"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; 

    function onYouTubePlayerAPIReady() {
     player = new YT.Player('player', {
     width:'320',
     height:'200',
     videoId:'%@',
     events: { 
    'onReady': onPlayerReady, 
    } 
    }); 
} 
function onPlayerReady(event) { 
event.target.playVideo(); 
} 

function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);  done = true; 
   } 

 if (event.data == YT.PlayerState.ENDED) {
 window.location = "callback:nil"; }; }

   function stopVideo() { 
 player.stopVideo();  

} 

</script> </body> </html>", [[NSUserDefaults standardUserDefaults] objectForKey:@"detailVideoURL"];

Image of the error :

I'm currently loading a YouTube video inside a -UIwebView, this is working perfectly and the video starts playing automatically. but the problem is that once the video finishes inside the -UIwebViewit just stops and shows the play button. I would however want the video player to close so the users wouldn't have to manually hit the "Done" button every time.

Image of the screen when the video doesn't close.

Here's the link I launch the video inside the -UIwebview

NSString *youTubeVideoHTML = [NSString stringWithFormat:@"<!DOCTYPE html><html><head>
<style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script>

    var tag = document.createElement('script'); tag.src = \"http://www.youtube./player_api\";
    var firstScriptTag = document.getElementsByTagName('script')[0]; 
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var player;

    function onYouTubePlayerAPIReady() { 
        player = new YT.Player('player', { 
            width:'320',
            height:'200',
            videoId:'%@',
            events: {
                'onReady': onPlayerReady,
            }
        });
    }

    function onPlayerReady(event) { 
        event.target.playVideo();
    }

</script> </body> </html>", [[NSUserDefaults standardUserDefaults]
objectForKey:@"detailVideoURL"]];

EDIT:

I tried implementing the first answer into my code and this is how it ended up like. I'm still unsure what I should add into the callback ?

NSString *youTubeVideoHTML = [NSString stringWithFormat:@"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script>
var tag = document.createElement('script'); tag.src = \"http://www.youtube./player_api\"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; 

    function onYouTubePlayerAPIReady() {
     player = new YT.Player('player', {
     width:'320',
     height:'200',
     videoId:'%@',
     events: { 
    'onReady': onPlayerReady, 
    } 
    }); 
} 
function onPlayerReady(event) { 
event.target.playVideo(); 
} 

function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);  done = true; 
   } 

 if (event.data == YT.PlayerState.ENDED) {
 window.location = "callback:nil"; }; }

   function stopVideo() { 
 player.stopVideo();  

} 

</script> </body> </html>", [[NSUserDefaults standardUserDefaults] objectForKey:@"detailVideoURL"];

Image of the error : http://gyazo./31da955d8af98f40b82789a7f60c1edb

Share Improve this question edited Oct 1, 2013 at 8:34 Master Stroke 5,1282 gold badges27 silver badges58 bronze badges asked Aug 12, 2013 at 11:30 Gretar AgnarssonGretar Agnarsson 992 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can do it by calling your objective function from javascript using youtube api.

On the HTML/Javascript Side

<html>
    <body>
        <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
        <div id="player"></div>

        <script>

            // 2. This code loads the IFrame Player API code asynchronously.
            var tag = document.createElement('script');
            tag.src = "http://www.youtube./player_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            // 3. This function creates an <iframe> (and YouTube player)
            //    after the API code downloads.
            var player;
            function onYouTubePlayerAPIReady() {
                player = new YT.Player('player', {
                                       height: '300',
                                       width: '250',
                                       videoId: 'GUdYebAN-Fs',
                                       events: {
                                       'onReady': onPlayerReady,
                                       'onStateChange': onPlayerStateChange
                                       }
                                       });
            }

            // 4. The API will call this function when the video player is ready.
            function onPlayerReady(event) {
                event.target.playVideo();
            }

            // 5. The API calls this function when the player's state changes.
            //    The function indicates that when playing a video (state=1),
            //    the player should play for six seconds and then stop.
            var done = false;
            function onPlayerStateChange(event) {
                 event.target.destroy();

                if (event.data == YT.PlayerState.PLAYING && !done) {
                    setTimeout(stopVideo, 60000);


                    done = true;
                }
                if (event.data == YT.PlayerState.ENDED) {

                      event.target.destroy();//to close the video
                      window.location = "callback:anything"; //here's the key
                };
            }
            function stopVideo() {
                player.stopVideo();
            }
            </script>
    </body>
</html>

onStateChange- From the google's API reference page

This event fires whenever the player's state changes. The data property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state.

So in the javascript function you would be able to trace the End of the video time.Then just
add event.target.destroy() on entering the state end condition.

On the native/iOS side:

And even you can do the native stuff here by catching up the call back method using the webview delegate method.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {


    if ( [[[request URL] scheme] isEqualToString:@"callback"] ) {

       //Video has ended up playing,you can perform native stuff here...

        return NO;
    }

    return YES;
}

Note: Please make sure to test this code in your device,because sometimes the simulators won't be supporting.

Good Luck...Hope it helps...

This is how you can apply Puneeth's solution to Google's YTPlayerView so the player hides after the video finishes:

- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state
{
    if(state == kYTPlayerStateEnded) {
        [self.youTubePlayer.webView stringByEvaluatingJavaScriptFromString:@"player.destroy();"];
        // you'll have to recreate the player again since it's now destroyed
        [self.youTubePlayer removeFromSuperview];
        self.youTubePlayer = nil;

    }
}
发布评论

评论列表(0)

  1. 暂无评论