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

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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值