您的位置:首页 > 移动开发 > Android开发

Android WebView中的JavaScript代码使用

2013-03-02 16:12 573 查看
  上一篇博文:Android WebView使用基础已经说了一些Android中WebView的基本使用。

  本篇文章主要介绍WebView中的JavaScript代码的执行相关,已经JS代码与Android代码的互相调用。

  (因为本人对Web开发并不是很熟悉,所以如果有哪些地方说得不对,还请指正。)

在WebView中使用JavaScript

  如果你想要载入的页面中用了JavaScript,你必须为你的WebView使能JavaScript。

  一旦使能之后,你也可以自己创建接口在你的应用和JavaScript代码间进行交互。

前情提要:使能JavaScript

  上一篇文章已经说过,可以通过
getSettings()
获得WebSettings,然后用
setJavaScriptEnabled()
使能JavaScript:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);


[b]绑定JavaScript与Android代码[/b]

  当你为你的Android应用中的WebView专门开发一个网页应用时,你可以创建你的JavaScript代码和你的客户端的Android代码之间的接口。

  比如,你可以用JavaScript代码调用Android代码中的方法,来展现一个对话框之类,而不是使用alert()方法(JS中的对话框方法)。

  在JS和Android代码间绑定一个新的接口,需要调用
addJavascriptInterface()
方法。

  方法参数传入一个Java对象实例和一个字符串,该字符串是一个名字(interface name,注意此接口不是通常所说的那个用来实现的接口,而是传入的这个对象在JS中的别名),在JS代码中用此名字调用该Java对象的方法。

  

  注意这个方法可以让JS代码控制宿主程序,这是一个非常有力的特性,但是同时也存在一些安全问题,因为进一步JS代码可以通过反射访问到注入对象的公有域。攻击者可能会在HTML和JavaScript中包含了有威胁性的代码。

  所以Android 4.1,API 17,也就是
JELLY_BEAN
开始,只有被JavascriptInterface 注解标识的公有方法可以被JS代码访问。

  另外,因为JS代码和Java对象在这个WebView所私有的后台线程交互,所以还需要注意线程安全性问题。

  注意,与JS代码绑定的的这个Java对象运行在另一个线程中,与创建它的线程不是一个线程。

  注意,这个Java对象的域是不可访问的。

[b]绑定JavaScript与Android代码的例子[/b]

  比如可以定义这么一个类:

/**
* 自定义的Android代码和JavaScript代码之间的桥梁类
*
* @author 1
*
*/
public class WebAppInterface
{
Context mContext;

/** Instantiate the interface and set the context */
WebAppInterface(Context c)
{
mContext = c;
}

/** Show a toast from the web page */
// 如果target 大于等于API 17,则需要加上如下注解
// @JavascriptInterface
public void showToast(String toast)
{
// Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
Toast.makeText(mContext, toast, Toast.LENGTH_LONG).show();
}
}


  然后将这个类和你的WebView中的JS代码绑定:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");


  给这个对象起的别名叫“Android”。

  这个就创立了一个接口名,叫“Android”,运行在WebView中的JS代码可以通过这个名字调用WebAppInterface类中的showToast()方法:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
function showAndroidToast(toast)
{
Android.showToast(toast);
}
</script>


[b]特别注意:需要设置chrome handler[/b]

  这个问题让我纳闷了好久,因为开始的时候我写的程序,JS代码中的按钮会出现在WebView中,但是点击下去后,不会弹出相应的对话框之类。

  也就是说JS代码调用自己也没有执行?

  同样的代码在别的地方执行可以正常弹出啊。所以我还提问来着:http://q.cnblogs.com/q/47060/

  后来找了半天原因,才发现两个问题:

  1.网页按钮按下后不出现JS对话框是因为没有设置chrome handler,需要设置如下: 

// 如果不设置这个,JS代码中的按钮会显示,但是按下去却不弹出对话框
// Sets the chrome handler. This is an implementation of WebChromeClient
// for use in handling JavaScript dialogs, favicons, titles, and the
// progress. This will replace the current handler.
myWebView.setWebChromeClient(new WebChromeClient()
{

@Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result)
{
// TODO Auto-generated method stub
return super.onJsAlert(view, url, message, result);
}

});


  

  2.调用Android代码的那个按钮也没有出现Toast是因为我把别名写错了(大小写没有注意)。(这个错误可以忽略,但是大家也要引以为戒。。Orz。。。)

[b]Android调用JavaScript代码[/b]

  这个还比较简单,需要调用的时候只需要一行代码:  

myWebView.loadUrl("javascript:myFunction()");


  其中myFunction()是JS函数。

  这里要补充一下,如果JavaScript函数是带参数的,那么调用时要特别注意。

  比如下面这个JS函数,在原来内容上加入一行:

function writeLine(string)
{
console.log("Write a new Line");//调试信息
document.getElementById("content").innerHTML += string + "<br />";//在content标签段落加入新行
}


  注:其中content是自定义的标签,html中有一个段落是:

<p id="content"></p>


  那么在Android代码中调用这个writeLine()函数时,需要传入一个字符串参数,比如,想要传入一个叫name的String:

myWebView.loadUrl("javascript:writeLine('"+name+"')");//JS代码要是带参数


  还有就是要注意双引号中的函数名一定不要写错。


程序实例

  做了一个程序:

activity_web_js.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".WebJSActivity" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/textView1"
android:text="@string/btn1_text" />

<WebView
android:id="@+id/myWebView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/textView1" />

</RelativeLayout>


参考资料

  Web学习网站:

  http://www.w3school.com.cn/

  API Guides: Building Web Apps in WebView

  http://developer.android.com/guide/webapps/webview.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: