Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override current Javascript functions with Android Webview

I'm porting my website to Android, and using an Webview to show the content to user. There are a lot of Javascript functions in my website, and I want to intercept them. I already seen a "solution" here.

However, I think there should be a more proper way, using Javascript Interface:

this.webView.addJavascriptInterface(this.webJavascriptInterface, "Android");

This way, I have to modify my website to call both myFunction() and Android.myFunction(). I tried to leave a blank String in the interface:

this.webView.addJavascriptInterface(this.webJavascriptInterface, "");

but the result was as I guess, it couldn't work. Is there a way to override current Javascript functions in Webview?

like image 375
Luke Vo Avatar asked Jul 03 '26 04:07

Luke Vo


2 Answers

// android
webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        webView.loadUrl("javascript:function inputClick(val){native.abcd(val);}");     // override js function
    }
});

webView.loadUrl("file:///android_asset/test.html");

webView.addJavascriptInterface(new Object() {
    @JavascriptInterface
    public void abcd(int val) {
        Log.e(TAG, "#js abcd" + val);
    }
}, "native");

<!-- html -->
<input type="button" onclick="inputClick(2)" value="button">

== add some explain at Sep 07,2015

because javascript function could be override, so you can override javascript function while page finished.

if not, normal implement maybe like this:

// js code
function inputClick(val) {
    native.abcd(val); // native and abcd defined in WebView method addJavascriptInterface
}

but this normal implement is seems not work in iOS(Object-C), and must edit HTML page. is just move the java-javascript bridge code from HTML to Java. (see method onPageFinished in example code)

like image 113
atearsan Avatar answered Jul 05 '26 18:07

atearsan


You can do this by injecting a new javascript that redefines old function, basically you can override existing function with this.

For example, to override window.print() function, I use this

webView.loadUrl("javascript:window.print = function() {Android.printPage();}")
like image 21
Alvian Avatar answered Jul 05 '26 18:07

Alvian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!