Android中WebView加载html页面时,JS 与客户端交互,传参

最近的项目中遇到了客户端编程与html 公用的情况,所以免不了会用到html中js与客户端的编程,所以研究了一下,希望与大家共享!

其实实现该功能的帖子网上一大堆,在这里我只说重点。

第一:不管你采用本地加载WebView 还是网络地址,只要在初始化webView 的时候添加如下代码即可:

webView.addJavascriptInterface(this, "<span style="color:#33ccff;background-color: rgb(255, 255, 255);">android</span>");
两个参数,第一个参数是为javaScript设置上下文,第二个参数其实就是用来标识调用者的Key.(个人理解)
下面我们写一个方法来响应javaScript中的Action
 <pre class="html" name="code"><pre class="html" name="code">/** 与js交互时用到的方法,在js里直接调用的 */
	@JavascriptInterface
	public void <span style="color:#ff0000;">startFunction</span>(String str) {

		Intent intent = new Intent();
		intent.putExtra("str", str);
		intent.setClass(this, SecondActivity.class);
		startActivity(intent);
	}

	@JavascriptInterface
	public void <span style="color:#ff0000;">startFunction</span>() {
		Intent intent = new Intent();
		intent.setClass(this, SecondActivity.class);
		startActivity(intent);
	}

可以看到以上两个方法一个是有参数的,一个是无参数的.
 
我们在写一个方法用来向js发起action
<pre class="html" name="code">	findViewById(R.id.bt).setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 无参数调用
			webView.loadUrl("javascript:<span style="color:#cc33cc;">javacalljs</span>()");
			// // 传递参数调用
			webView.loadUrl("javascript:<span style="color:#cc33cc;">javacalljswithargs</span>("
					+ "'hello world'" + ")");
		}
	});

 
至此客户端编程基本上完事了,下面我们看一下html页面的js怎么写。
<html>
<head>
<meta http-equiv="Content-Type"	content="text/html;charset=UTF-8">
<script type="text/javascript">
function <span style="color:#cc33cc;">javacalljs</span>(){
	 document.getElementById("content").innerHTML +=   
         "<br\>java调用了js函数";
}

function <span style="color:#cc33cc;">javacalljswithargs</span>(arg){
	 document.getElementById("content").innerHTML +=   
         ("<br\>"+arg);
}

</script>
</head>
<body>
this is my html <br/><br/><br/>
<a onClick="window.<span style="color:#33ccff;">android.</span><span style="color:#ff0000;">startFunction</span>()">点击调用java代码</a><br/><br/><br/>
<a onClick="window.<span style="color:#33ccff;">android</span>.<span style="color:#ff0000;">startFunction</span>('传参--hello world')" >点击调用java代码并传递参数</a>
<br/><br/><br/>
<div id="content">内容显示</div><br/><br/>
</body>
</html>
如上代码需要注意的地方我都已经加了颜色标记了,一看就明白了吧 !
附上代码:<a target=_blank href="http://download.csdn.net/detail/qq446869111/8236569">http://download.csdn.net/detail/qq446869111/8236569</a>
 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值