如果你想要载入的页面中用了javascript,你必须为你的webview使能javascript。一旦使能之后,你也可以自己创建接口在你的应用和javascript代码间进行交互。
可以通过getsettings()获得websettings,然后用setjavascriptenabled()使能javascript:
webview mywebview = (webview) findviewbyid(r.id.webview);websettings websettings = mywebview.getsettings();websettings.setjavascriptenabled(true);
绑定javascript与android代码
当你为你的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对象的域是不可访问的。
绑定javascript与android代码的例子
比如可以定义这么一个类:
/** * 自定义的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>
特别注意:需要设置chrome handler
两个问题:
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是因为我把别名写错了(大小写没有注意)。
android调用javascript代码
这个还比较简单,需要调用的时候只需要一行代码:
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代码要是带参数
还有就是要注意双引号中的函数名一定不要写错。
程序实例
效果如下:
界面中包含一个textview,旁边一个button,下面整个是一个webview。
在webview中载入了一个本地html文件,本地文件存放在assets文件夹中。
网页中前四个按钮调用的是javascript函数,显示各种对话框。
sayhello按钮调用android代码中的一个方法,显示一个toast,如图中所示。
为了证明android也可以调用js代码,最上方的android button按下后和“点击这里”那个按钮的效果一致,都是出现js的对话框。
activity代码:
package com.example.hellowebjs; import android.annotation.suppresslint; import android.app.activity; import android.content.context; import android.os.bundle; import android.view.view; import android.webkit.jsresult; import android.webkit.webchromeclient; import android.webkit.websettings; import android.webkit.webview; import android.webkit.webviewclient; import android.widget.button; import android.widget.toast; public class webjsactivity extends activity{ private webview mywebview = null; private button mybutton = null; @suppresslint("setjavascriptenabled") @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_web_js); mywebview = (webview) findviewbyid(r.id.mywebview); // 得到设置属性的对象 websettings websettings = mywebview.getsettings(); // 使能javascript websettings.setjavascriptenabled(true); // 支持中文,否则页面中中文显示乱码 websettings.setdefaulttextencodingname("gbk"); // 限制在webview中打开网页,而不用默认浏览器 mywebview.setwebviewclient(new webviewclient()); // 如果不设置这个,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); } }); // 用javascript调用android函数: // 先建立桥梁类,将要调用的android代码写入桥梁类的public函数 // 绑定桥梁类和webview中运行的javascript代码 // 将一个对象起一个别名传入,在js代码中用这个别名代替这个对象, 可以调用这个对象的一些方法 mywebview.addjavascriptinterface(new webappinterface(this), "myinterfacename"); // 载入页面:本地html资源文件 mywebview.loadurl("file:///android_asset/sample.html"); // 这里用一个android按钮按下后调用js中的代码 mybutton = (button) findviewbyid(r.id.button1); mybutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // 用android代码调用javascript函数: mywebview.loadurl("javascript:myfunction()"); // 这里实现的效果和在网页中点击第一个按钮的效果一致 } }); } /** * 自定义的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(); } }}
html文件:
<html> <head> <h1> this is a html page </h1> <!-- javascript脚本,主要包括了按钮要执行的函数,显示对话框等 --> <script type="text/javascript"> //javascript方法,弹出对话框显示信息 function myfunction() { alert("hello world!"); } function onalert() { console.log("onalert method"); //显示调试信息 alert("this is a alert sample from html"); } function onconfirm() { console.log("onconfirm method"); var b = confirm("are you sure to login?"); alert("your choice is " + b); } function onprompt() { console.log("onprompt method"); var b = prompt("please input your password", "aaa"); alert("your input is " + b); } //调用绑定的java对象的方法,即调用android代码显示对话框 function showandroidtoast(toast) { console.log("showandroidtoast method"); myinterfacename.showtoast(toast); //注意此处的myinterfacename要和外部传入的名字一致,大小写正确 } </script> </head> <body> <p> <!-- 前四个按钮调用js函数 --> javascript函数调用 <br /> <button onclick="myfunction()">点击这里!</button> <br /> <input type="button" value="alert" onclick="onalert()" /> <br /> <input type="button" value="confirm" onclick="onconfirm()" /> <br /> <input type="button" value="prompt" onclick="onprompt()" /> <br /> <!-- 上面用了两种定义按钮的方式,效果一样的 --> </p> <p> <!-- 这个say hello 按钮调用android代码中的方法 --> 用javascript按钮调用android代码 <br /> <input type="button" value="say hello" onclick="showandroidtoast('hello android!')" /> </p> <a href="http://www.google.com" />google </a> </body> </html>
activity布局文件:
<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>
更多编程相关知识,请访问:编程教学!!
以上就是在webview中使用javascript的方法介绍的详细内容。