了解Android webview javascript界面

前端之家收集整理的这篇文章主要介绍了了解Android webview javascript界面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个 android WebView,并使用add JavascriptInterface(mObject,“jsinterface”)注入了javascript接口.它工作正常,直到我使用new运算符在 JavaScript中创建一个具有相同名称(jsinterface)的对象.

我的Java代码

@H_301_4@WebView mWebView = findViewById(R.id.myWebView); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebChromeClient(new MyWebChromeClient((Activity)mContext)); mWebView.addJavascriptInterface(new testClass(),"jsinterface"); mWebView.loadUrl("UrlToLoad");

testClass.java

@H_301_4@public class testClass{ public testClass() { } @JavascriptInterface public String testNativeMethod() { return "Java method called!!"; } }

我的Java脚本代码

test.js

@H_301_4@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"

问题:

这可能是javascript对象可以访问两者,即javascript方法和本机JAVA方法(通过javascript接口暴露给它)?是否有可能将任何属性设置为webview或执行任何JS脚本来完成此操作?

解决方法

尝试

您可以尝试创建另一个对象,该对象将重新调用对javascript接口的调用.在WebViewClient中实现onPageStarted方法,并以下列方式在onPageStarted方法中注入javascript.

@H_301_4@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); } });

希望这可以帮助 :-)

猜你在找的Android相关文章