如何从Java调用javascript函数时的WebView页不同 [英] How to call javascript function from java when webview page is different
问题描述
我使用HTML和web视图显示在Android项目。
I am working on an android project using HTML and webview to display.
我
display.loadUrl("file:///android_asset/index.html");
display.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url)
{
display.loadUrl("javascript:openDialog()");
}
});
和这个完美的作品。但是javascript函数我想打电话给在另一页(chat.html)。如何从Java调用这个页面的JavaScript功能?
and this works perfectly. But the javascript function i want to call is in another page (chat.html). How do i call the javascript functions on this pages from java?
推荐答案
如果您是网页(chat.html)的所有者,您可以集成一个JS-函数调用本地方法。而在此本机方法,你可以打电话给你的目标JS:
If you are the owner of the webpage (chat.html), you can integrate a JS-function which invokes a native method. And in this native method you can call your target-JS:
chat.html:
chat.html:
function callItNow() {
if (typeof Android != "undefined"){
if (Android.caller!= "undefined") {
Android.caller();
}
}
}
在本地code,定义一个类:
in native Code, define a class:
class MyJavascriptBridge {
public void caller() {
//now you know you are on the right place (chat.html)
webView.loadUrl("javascript:openDialog()");
}
}
当然,你必须桥申报的网页视图:
and of course you have to declare the bridge to your webview:
webView.addJavascriptInterface(new MyJavascriptBridge(), "Android");
这篇关于如何从Java调用javascript函数时的WebView页不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!