了解Android webview javascript界面

Uma*_*war 7 javascript java android webview

我创建了一个android WebView,并javascript使用注入接口addJavascriptInterface(mObject, "jsinterface").它工作正常,直到我使用new运算符在JavaScript中创建具有相同名称(jsinterface)的对象.

我的Java代码:

WebView mWebView = findViewById(R.id.myWebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient((Activity)mContext));
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
mWebView.loadUrl("UrlToLoad");
Run Code Online (Sandbox Code Playgroud)

testClass.java

public class testClass{
    public testClass() {
    }

    @JavascriptInterface
    public String testNativeMethod() {
        return "Java method called!!";
    }
}
Run Code Online (Sandbox Code Playgroud)

我的Java脚本代码

test.js

function test(msg){
    this.message = msg;

    this.testJSMethod = function(){
        return this.message;
    }
}

alert(jsinterface.testNativeMethod()); // prints Java method called!!
jsinterface= new test("JS method called...");
alert(jsinterface.testJSMethod()); // prints JS method called...
alert(jsinterface.testNativeMethod()); // errors "NPMethod called on non- NPObject"
Run Code Online (Sandbox Code Playgroud)

问题:

这是可能的javascript对象都可以访问两个,即 javascript方法和本地JAVA方法(通过接触到它javascriptinterface)?有没有可能设置任何属性webview或执行任何JS script来完成这项工作?

kri*_*son 7

想想document在javascript中.当您在Web浏览器中时,这是一个您可以随时访问的全局对象.如果你自己new调用var document,那么访问全局会遇到问题document.

执行此行时:

    mWebView.addJavascriptInterface(new testClass(), "jsinterface");
Run Code Online (Sandbox Code Playgroud)

您正在添加一个名为的全局对象jsinterface.这与情况相同document.如果创建具有相同名称的var,则它将覆盖现有的全局引用.

添加javascript界面​​后WebView,您无需创建new对该界面的引用. addJavascriptInterface已经为你做了这件事.


Aow*_*aza 5

尝试

您可以尝试创建另一个对象,该对象将通过以下方式重新转换对 javascript interface.ImplementonPageStarted方法的调用WebViewClient,并在onPageStarted方法中注入 javascript 。

 mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
        @Override
        public void onPageStarted (WebView view, String url, Bitmap favicon){
            String jsScript= "javascript:var functions_array = ['testNativeMethod'];";
                   jsScript+="var jsinterface = {};"
                   jsScript+="functions_array.map(function(id){"
                   jsScript+="jsinterface[id]= function() {"
                   jsScript+="try{return temp_obj[id].apply(temp_obj, arguments);}"
                   jsScript+="catch(e) { console.log('ERROR: ' + e + ', method ' + id);"
                   jsScript+="return false;}}})"
            view.loadUrl(jsScript);
        }
    });
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :-)