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

守給你的承諾、 提交于 2020-03-07 17:42:40

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!