Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple trick to autoplay an html5 video element in a webview. (inject javascript to play on load)
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webview;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { webview.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("http://html5demos.com/video");
}
@Override
protected void onPause() {
super.onPause();
webview.onPause();
}
@Override
protected void onResume() {
webview.onResume();
super.onResume();
}
}
@prasad456

This comment has been minimized.

Copy link

commented Dec 8, 2015

I cant see video but its playing I can hear audio of video

@jessevanmuijden

This comment has been minimized.

Copy link

commented Jan 8, 2016

same here @prasad456

@taofik-nos

This comment has been minimized.

Copy link

commented Apr 13, 2016

Same here, only audio is playing.

@bhaveshintorque

This comment has been minimized.

Copy link

commented Jul 21, 2016

Add android:hardwareAccelerated="true" in application Menifist

@JhonathamBrazil

This comment has been minimized.

Copy link

commented Jun 29, 2017

I'm having a similar problem, I use several YouTube videos on my site, and auto-play does not work.

My site is this www.pipocaplayfm.com/mobile_play

I mounted a webview app, but it does not work ... can you help me?

@meetvora-ecosmob

This comment has been minimized.

Copy link

commented Dec 20, 2018

This might help:

@Override
protected void onResume() {
    webView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
    super.onResume();
}

I've added that JavaScript code in onResume.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.