I'm developing an app using PhoneGap. So, it's a web app. In this app, I have a requirement to embed a YouTube video and autoplay it whenever the user navigates to that particular page.
I've read that HTML5 video autoplay doesn't work on mobile devices because of bandwidth concers. My question is that is there any way at all to bypass this restriction? I don't mind complex workarounds or hacks that could allow me to do this. Anything at all.
Thanks.
As you pointed out yourself, all autoplay instructions in your code itself will be ignored on load. So we'll implement a function that gets the video in the body and starts playing it.
The following javascript code could do this:
(function() {
document.getElementsByTagName('video')[0].play();
})()
To execute this code after the page has loaded, we need to set a WebViewClient and implement onPageFinished()
webview.setWebViewClient(new CordovaWebViewClient(this, webview) {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { webview.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setPluginState(WebSettings.PluginState.ON);
A full example:
webview = new CordovaWebView(this);
setContentView(webview);
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new CordovaWebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { webview.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
webview.loadUrl("http://html5demos.com/video");
There is a cordova/phonegap plugin that promises to do this. It rely on the Webview method setMediaPlaybackRequiresUserGesture, added in API level 17 (Android 4.2).
It simply call this method on the webview:
WebView view = getWebViewFromPlugin();
view.getSettings().setMediaPlaybackRequiresUserGesture(false);
It's also available in phongap build.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With