How to auto play iframe youtube on webview android

2020-04-07 04:12发布

I use android webview in my app for display video from youtube it's work well.

But i want it's auto play.

This is my activity i append "?autoplay=1" to videoUrl but nothing change it's still not auto play.

public class LandVideoAct extends Activity {
    WebView mWebView;
    String videoURL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.landfull);
        videoURL = "http://www.youtube.com/embed/VYIi49czywo?autoplay=1";
        mWebView = (WebView) findViewById(R.id.fullwebview);

        String vid = "<html><body style=\"margin: 0; padding: 0\"><iframe  width=\"100%\" height=\"100%\" src=\""+videoURL+"\" type=\"text/html\" frameborder=\"0\"></iframe><body><html>";

        WebChromeClient mWebChromeClient = new WebChromeClient(){
            public void onProgressChanged(WebView view, int newProgress) {
            }
        };

        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); 
            }
        });
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.setInitialScale(1);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        if (Build.VERSION.SDK_INT < 17) {
            Log.i("GPSNETWORK", "<17");
        } else {
            Log.i("GPSNETWORK", Build.VERSION.SDK_INT+">=17");
            mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        }
        mWebView.loadData(vid, "text/html", "UTF-8");
    }
}

7条回答
聊天终结者
2楼-- · 2020-04-07 04:51

A little late but I hope this helps.

After your page is finished loading run this:-

 yourWebView.loadUrl("javascript:(function() { document.getElementsByClassName('ytp-large-play-button ytp-button')[0].click(); })()");
查看更多
登录 后发表回答