How to check if webview YouTube video player was started

Kenneth Browning

In my Android app, I have a webview where there is an embedded YouTube video inside the webview. My app has a native AdMob banner.

I'd like to hide the native admob banner from the app when user plays the video, so the banner does not show while the video is playing and then show the ads again when the video stops playing

The issue is that I do not know how to check if the video was started or stopped.

Any idea how this can be done? Thanks much.

Rahul Khurana

The communication between webview and native are done through JavascriptInterface. YouTube has built it's API in a similar fashion. you can use the below code to achieve what you want.

To achieve the play/pause functionality via Youtube video you can use YouTube JavaScript Player API.

Example:

<div id="video-placeholder"></div>

<script src="https://www.youtube.com/iframe_api"></script>

When the API is fully loaded, it looks for a global function called onYouTubeIframeAPIReady() which you should define.

Your code should look something like this

var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('video-placeholder', {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {
            color: 'white',
            playlist: 'taJ60kskkns,FG0fTKAqZ5g'
        },
        events: {
            onReady: initialize
        }
    });
}

Just make two buttons and call the needed method on click.

$('#play').on('click', function () {
    player.playVideo();
});

$('#pause').on('click', function () {
    player.pauseVideo();
});

You can use JavascriptInterface to get the callback inside the native java/kotlin code from WebView.

More details info

  1. Youtube javascript player API with example

  2. JavaScript Interface with example

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related