Intercepting HTML5 video source request in Android WebView

被刻印的时光 ゝ 提交于 2019-12-04 06:15:33

I solved the problem using a javascript approach. When the HTML page is loaded, a loadedmetadata event is fired when the video metadata has been loaded. From that moment on you can get the selected video source from the currentSrc attribute of the video element and pass it via a JavascriptInterface to the Android native code.

Below is the code of the HTML5 video element. "Android" is the name by which the JavascriptInterface can be accessed in javascript.

<video poster="image/poster.jpg" height="240" width="360" onloadedmetadata="Android.interceptPlay(this.currentSrc);">
    <source src="video/BigBuck.m4v">
    <source src="video/BigBuck.webm" type="video/webm">
    <source src="video/BigBuck.theora.ogv" type="video/ogg">
    HTML5 video not supported.
</video>

The code of the JavascriptInterface

private class JavaScriptInterface {
    Context mContext;

    /* Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    public void interceptPlay(String source) {
        // do something
    }
}

And finally add the JavascriptInterface to the WebView at Activity creation time

mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

It’s important to catch the loadedmetadata event by adding the onloadedmetadata attribute to the HTML5 video element and not by registering an event listener at page load via addEventListener("loadedmetadata",...) because on a fast network the loadedmetadata event may be fired before the listener is registered (see http://dev.opera.com/articles/view/consistent-event-firing-with-html5-video)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!