java - 使用 Javascript 从 WebView 调用 Activity 的方法

标签 java javascript android webview

我正在从我的 WebView 调用一个方法。每当单击 WebView 中的按钮时,该方法都会执行 Toast。它工作正常,但当我传递参数时它不起作用。当我传递参数时,该方法没有被执行。

这是我在 strings.xml 中的 javascript -

<string name="details">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width; user-scalable=0;&quot; /&gt;
&lt;title&gt;My HTML&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;MyHTML&lt;/h1&gt;
&lt;p id=&quot;mytext&quot;&gt;Hello!&lt;/p&gt;
&lt;input type=&quot;button&quot; value=&quot;Say hello&quot; onClick=&quot;showAndroidToast('Hello world!')&quot; /&gt;
&lt;script language=&quot;javascript&quot;&gt;
   function showAndroidToast(toast) {
       AndroidFunction.showToast(toast);
   }
   function callFromActivity(msg){
 document.getElementById(&quot;mytext&quot;).innerHTML = msg;
   }
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</string>

这是我的 Activity 代码-

String str = "<html><body>"
            + getString(R.string.details)
            + "</body></html>";
    webview.addJavascriptInterface(new MyJavaScriptInterface(this),
            "AndroidFunction");

    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webview.loadDataWithBaseURL(null, str, "text/html", "utf-8", null);

这是我的 MyJavaScriptInterface 类:

public class MyJavaScriptInterface {
    Context mContext;

    MyJavaScriptInterface(Context c) {
        Log.d("tag", "cls");
        mContext = c;
    }

    public void showToast(String toast) {//without the argument this method executes
        Log.d("tag", "msg");
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

}

最佳答案

您的 JavaScript 语法不正确:

function showAndroidToast(String toast) {
    AndroidFunction.showToast(String toast);
}

需要:

function showAndroidToast(toast) {
    AndroidFunction.showToast(toast);
}

其他提示:

  1. 您通过包装 getString() 来复制 HTML 标记。与 <html><body> 。这已经包含在您的 strings.xml 中:

    webview.loadDataWithBaseURL(null, getString(R.string.details), "text/html", "utf-8", null);

  2. 您不应该将所有 HTML 存储在 strings.xml 中。将其作为 HTML 文件存储在 Assets 文件夹中并调用:

    webview.loadUrl("file:///android_asset/details.html");

  3. 你不应该使用这样的侵入性Javascript,这将是以后维护的一场噩梦。阅读this article了解更好的普通 Javascript 开发方法。

关于java - 使用 Javascript 从 WebView 调用 Activity 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19858028/

相关文章:

java - Java中的单例模式和静态类有什么区别?

java - Spring Hibernate MySQL- 50k 插入耗时 20 分钟

javascript - JavaScript 保证输出 "[object X]"吗?

javascript - jQuery Datepicker 日期范围填充内联日历

android - 如何让 Action Bar SearchView 填满整个 action bar?

java - 如何在spring中显示具有帐户状态的用户列表

java - 在没有 Maven 的情况下使用 Jclouds

javascript - 图像作为按钮

Android - ListView 中的 Intent

Android的SoundPool不播放任何声音