Android的调用web视图中的JavaScript函数 [英] Android Calling JavaScript functions in WebView

查看:155
本文介绍了Android的调用web视图中的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用一些JavaScript函数坐在一个html页面运行的是Android的WebView内。 pretty的简单什么code尝试做如下 - 从Android应用程序,调用一个带有测试消息,它依次调用Java函数回在Android应用程序,通过敬酒显示测试消息的JavaScript函数

JavaScript函数如下:

 函数testEcho(消息){
     window.JSInterface.doEchoTest(消息);
}
 

从web视图,我曾尝试调用JavaScript通过以下方式,没有运气:

  myWebView.loadUrl(!JavaScript的:testEcho(世界您好));
mWebView.loadUrl(javascript的:(函数(){+!testEcho(的Hello World);+})());
 

我没有启用JavaScript在web视图

  myWebView.getSettings()setJavaScriptEnabled(真)。
//注册包含方法的类暴露给JavaScript
myWebView.addJavascriptInterface(myJSInterfaceJSInterface);
 

和继承人的Java类

 公共类JSInterface {

私人的WebView mAppView;
公共JSInterface(的WebView appView){
        this.mAppView = appView;
    }

    公共无效doEchoTest(字符串回声){
        吐司面包= Toast.makeText(mAppView.getContext(),回声,Toast.LENGTH_SHORT);
        toast.show();
    }
}
 

我已经花了很多时间在Google上搜寻四周,看看有什么我可能是做错了。所有的例子我发现使用这种方法。有谁看到了什么在这里?

编辑:有被引用和放几个其他外部JavaScript文件;在HTML中使用,可能他们是问题?

解决方案

我想出什么问题是:缺少引号在testEcho()的参数。这是我接到电话的工作:

  myWebView.loadUrl(JavaScript的:testEcho(您好!世界));
 

I am trying to call some javascript functions sitting in an html page running inside an android webview. Pretty simple what the code tries to do below - from the android app, call a javascript function with a test message, which inturn calls a java function back in the android app that displays test message via toast.

The javascript function looks like:

function testEcho(message){
     window.JSInterface.doEchoTest(message);
}

From the WebView, I have tried calling the javascript the following ways with no luck:

myWebView.loadUrl("javascript:testEcho(Hello World!)");
mWebView.loadUrl("javascript:(function () { " + "testEcho(Hello World!);" + "})()");

I did enable javascript on the WebView

myWebView.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
myWebView.addJavascriptInterface(myJSInterface, "JSInterface"); 

And heres the Java Class

public class JSInterface{

private WebView mAppView;
public JSInterface  (WebView appView) {
        this.mAppView = appView;
    }

    public void doEchoTest(String echo){
        Toast toast = Toast.makeText(mAppView.getContext(), echo, Toast.LENGTH_SHORT);
        toast.show();
    }
}

I've spent a lot of time googling around to see what I may be doing wrong. All examples I have found use this approach. Does anyone see something wrong here?

Edit: There are several other external javascript files being referenced & used in the html, could they be the issue?

解决方案

I figured out what the issue was : missing quotes in the testEcho() parameter. This is how I got the call to work:

myWebView.loadUrl("javascript:testEcho('Hello World!')");

这篇关于Android的调用web视图中的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆