A
A
Alex2021-01-28 18:49:00
Java
Alex, 2021-01-28 18:49:00

How to secure JavascriptInterface methods while tracking WebView URL?

There is JavascriptInterface class for JS interaction in WebView and Java android.

Class
class JavaScriptInterface {
Context mContext;
WebView mW;
JavaScriptInterface(Context c,WebView w) {
    mContext = c;
    mW = w;
}
@JavascriptInterface
public void saveJson(String json) {
    if(mW.getUrl().indexOf("file:///android_asset/") == 0){
        if(mContext instanceof MainActivity)
            ((MainActivity)mContext).saveFL(json);
    }
}
@JavascriptInterface
public String loadJson() {
    if(mW.getUrl().indexOf("file:///android_asset/") == 0){
        if(mContext instanceof MainActivity)
           return ((MainActivity)mContext).loadFL();
    }
    return "[]";
}

And for security purposes, you want to call methods from the JavascriptInterface class only if the URL matches internal resources. But the implementation above throws an error on the line with mW.getUrl :
A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread.

How can I pass the current URL in WebView to JavascriptInterface methods? Or maybe there is a better option to make a check so that these functions cannot be run on other sites?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-01-28
@alexjet73

I would look towards adding/removing JavascriptInterface somewhere around WebViewClient::onPageStarted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question