Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

javascript - Android在WebView中调用JavaScript函数(Android Calling JavaScript functions in WebView)

I am trying to call some javascript functions sitting in an html page running inside an android webview .

(我试图调用一些javascript函数坐在一个运行在android webview内的html页面。)

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.

(很简单代码试图在下面做什么 - 从Android应用程序,调用带有测试消息的javascript函数,其中inturn在android应用程序中调用java函数,通过toast显示测试消息。)

The javascript function looks like:

(javascript函数看起来像:)

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

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

(从WebView,我尝试通过以下方式调用javascript ,没有运气:)

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

I did enable javascript on the WebView

(我确实在WebView上启用了javascript)

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

And heres the Java Class

(继续Java类)

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?

(编辑:html引用和使用了其他几个外部javascript文件,它们可能是问题吗?)

  ask by user163757 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figured out what the issue was : missing quotes in the testEcho() parameter.

(我弄清楚问题是什么:testEcho()参数中缺少引号。)

This is how I got the call to work:

(这就是我接到工作的方式:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...