使用Javascript从WebView调用Activity的方法

时间:2013-11-08 11:29:17

标签: java javascript android webview

我正在调用WebView中的方法。只要点击Toast中的按钮,该方法就会执行WebView。它工作正常,但当我通过一个参数它不起作用。当我传递一个参数时,该方法没有被执行。

这是javascript中的strings.xml -

<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's代码 -

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();
    }

}

2 个答案:

答案 0 :(得分:1)

您的Javascript语法不正确:

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

需要:

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

其他提示:

  1. 您正在使用getString()包裹<html><body>来复制HTML标记。这已包含在您的strings.xml

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

  2. 您不应将所有HTML存储在strings.xml中。将其作为HTML文件存储在您的资源文件夹中,然后调用:

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

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

答案 1 :(得分:1)

我们在方法调用中不使用变量类型。

更改

AndroidFunction.showToast(String toast);

AndroidFunction.showToast(toast);