首页 > 移动平台 > 详细

iOS中UIWebView与其中网页的javascript的交互

时间:2015-12-11 02:13:49      阅读:333      评论:0      收藏:0      [点我收藏+]

首发:个人博客,更新&纠错&回复

1.本地语言调js的方式与android中的方式类似,也是向WebView控件发送要调用的js语句
2. 但js调本地语言,则不是像android那样直接调一个全局变量的方法,而是通过location.href=xx://yy这样的方式触发UIWebViewDelegate接口实现者的webView shouldStartLoadWithRequest navigationType方法,该方法应该判断目标路径(即xx://yy)的schema(即xx)是否实际是要调用swift,如果是,则按约定执行之,并返回false阻止网页路径变化,如果不是要调用swift,则返回true,让改网页继续正常加载目标url。
android和iOS对比,它们都用了伪url的技术,但android是在本地语言调js时使用了伪url(该url的schema为javascript),而iOS是js调本地语言时使用了伪url(该url是自定义的标识),这个错落很有意思。
?
?

swift代码:

import?UIKit

?

class?ViewController:?UIViewController,?UIWebViewDelegate?{

?? ?

? ??@IBOutlet?weak?var?theWebView:?UIWebView!

?? ?

? ??override?func?viewDidLoad() {

? ? ? ??//加载本地html

? ? ? ??let?res =?NSBundle.mainBundle().pathForResource("index",ofType:"html")

? ? ? ??let?url =?NSURL(fileURLWithPath: res!);

? ? ? ??let?request =?NSURLRequest(URL: url);

? ? ? ??self.theWebView.loadRequest(request);

? ? ? ??self.theWebView.delegate?=?self;

? ??}

?? ?

? ??//让js可以调用swift

? ??func?webView(webView:?UIWebView, shouldStartLoadWithRequest request:?NSURLRequest, navigationType:?UIWebViewNavigationType) ->?Bool?{

? ? ? ??//判断是不是js在调用swift,如果是,则处理并返回false

? ? ? ??if(request.URL!.scheme?==?"myschema"){

? ? ? ? ? ??let?host = request.URL!.host;

? ? ? ? ? ??if(host ==?"go"){

? ? ? ? ? ? ? ??let?query = request.URL!.query!;

? ? ? ? ? ? ? ??print(query);

? ? ? ? ? ? ? ??let?split = query.componentsSeparatedByString("=");

? ? ? ? ? ? ? ??let?text = split[1];

? ? ? ? ? ? ? ??self.theWebView.stringByEvaluatingJavaScriptFromString("changeContent(\""?+ text +?"\")");

? ? ? ? ? ??}

? ? ? ? ? ??return?false;

? ? ? ??}else{

? ? ? ? ? ??return?true;

? ? ? ??}

? ??}

?? ?

? ??//swift调用js

? ??@IBAction?func?btnClicked(sender:?AnyObject) {?

? ? ? ??self.theWebView.stringByEvaluatingJavaScriptFromString("changeContent(\"123\")");

? ??}

}

?

网页代码:

<!DOCTYPE html>

<html>

<head>

? ??<meta?charset="utf-8">

</head>

<body>

? ??<span?id="theSpan"></span>

? ??<button?onclick="doIt()">js调用swift</button>

? ??<input?type="text"?id="t">

? ??<script>

? ? ? ??//swift可以调用js

? ? ? ??function?changeContent(str){

? ? ? ? ? ??document.getElementById(‘theSpan‘).innerHTML = str;

? ? ? ??}

? ? ? ??//js调用swift

? ? ? ??function?doIt(){

? ? ? ? ? ??document.location.href =?"myschema://go?a="?+ document.getElementById("t").value;

? ? ? ??}

? ??</script>

</body>

?

</html>

长期欢迎项目合作机会介绍,项目收入10%用于酬谢介绍人。新浪微博:@冷镜,QQ:908789432

iOS中UIWebView与其中网页的javascript的交互

原文:http://zidafone.iteye.com/blog/2263042

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!