I am testing my app on Android N and trying to load youtube pages in my webview and autoplaying them. This is my onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TestWebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
mWebView.loadUrl("https://www.youtube.com/watch?v=hzz_6dmv03I?autoplay=1");
//mWebView.loadUrl("https://vimeo.com/117116735");
}
The above does not autoplay the youtube or vimeo video upon loading the page. I also tried adding the following to my TestWebViewClient
public class TestWebViewClient extends WebViewClient {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
}
}
This actually succeeds in autoplaying the vimeo video link but when I use it on the youtube video link then I get the following error:
Uncaught TypeError: Cannot read property 'play' of undefined
For the youtube video I also tried simulating a click on the play button after looking up its class name but that also does not work:
public class TestWebViewClient extends WebViewClient {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() {
document.getElementsByClassName('ytp-play-button')[0].click();
})");
}
}
Please let me know if there is a solution to this that does not involve using the Youtube Data API.