加载JavaScript功能的Andr​​oid奇巧到的WebView [英] Loading javascript functions to webview in Android Kitkat

查看:190
本文介绍了加载JavaScript功能的Andr​​oid奇巧到的WebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有加载JavaScript函数,这是在外部文件,到Android的奇巧的WebView问题。我的早期版本的做法是,我实现了我自己的WebView客户端和方法onPageFinisned我打电话

I am having problems with loading javascript functions, which are in external file, into webview in Android Kitkat. My approach for earlier versions was that i implemented my own webview client and in method onPageFinisned i called

mWebView.loadUrl("javascript:" + functions);

后,当我想叫一些JS的方法,我称之为同一code,像

later, when i wanted to call some js method, i call same code, like

mWebView.loadUrl("javascript:" + someFunction);

在Android的奇巧有新的方法evaluateJavascript,它取代我的code。与调用该JavaScript函数。我的问题是,现在这个老方法抛出这个错误:

In android kitkat there is new method evaluateJavascript, which replaces my code with calling that javascript functions. My problem is that now this and old approach throw this error:

Uncaught ReferenceError: function is not defined

看来,问题出在装载了JavaScript功能的WebView,但我不知道如何加载其他方式。谢谢

It seems that problem is in loading that javascript functions to webview but i dont know how to load it other way. Thanks

推荐答案

什么工作对我来说是有一个网页中的JavaScript函数,在<脚本> 标签:

What works for me is to have the JavaScript functions inside a Web page, in <script> tags:

<html>
<head>
<title>Android GeoWebTwo Demo</title>
<script language="javascript">
    function whereami(lat, lon) {
        document.getElementById("lat").innerHTML=lat;
        document.getElementById("lon").innerHTML=lon;
    }

    function pull() {
        var location=JSON.parse(locater.getLocation());

        whereami(location.lat, location.lon);
    }
</script>
</head>
<body>
<p>
You are at: <br/> <span id="lat">(unknown)</span> latitude and <br/>
<span id="lon">(unknown)</span> longitude.
</p>
<p><a onClick="pull()">Update Location</a></p>
</body>
</html>

随后,我可以成功地使用 evaluateJavascript()

public void onLocationChanged(Location location) {
  StringBuilder buf=new StringBuilder("whereami(");

  buf.append(String.valueOf(location.getLatitude()));
  buf.append(",");
  buf.append(String.valueOf(location.getLongitude()));
  buf.append(")");

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    browser.evaluateJavascript(buf.toString(), null);
  }
  else {
    browser.loadUrl("javascript:" + buf.toString());
  }
}

(均为code片段是从这个示例应用程序

这适用于新老版本的Andr​​oid。现在,在我的情况,我的JavaScript恰好与DOM搞乱,所以我需要一个网页反正。你可能有一个空的&LT;车身方式&gt; ,与网页只是为了提供JavaScript函数

This works on old and new versions of Android. Now, in my case, my JavaScript happens to be messing with the DOM, so I needed a Web page anyway. Yours might have an empty <body>, with the Web page just there to supply the JavaScript functions.

这篇关于加载JavaScript功能的Andr​​oid奇巧到的WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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