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

首发:我的博客,更新&纠错&回复javascript

1.本地语言调js的方式与android中的方式相似,也是向WebView控件发送要调用的js语句html

2. 但js调本地语言,则不是像android那样直接调一个全局变量的方法,而是经过location.href=xx://yy这样的方式触发UIWebViewDelegate接口实现者的webView shouldStartLoadWithRequest navigationType方法,该方法应该判断目标路径(即xx://yy)的schema(即xx)是否实际是要调用swift,若是是,则按约定执行之,并返回false阻止网页路径变化,若是不是要调用swift,则返回true,让改网页继续正常加载目标url。java

android和iOS对比,它们都用了伪url的技术,但android是在本地语言调js时使用了伪url(该url的schema为javascript),而iOS是js调本地语言时使用了伪url(该url是自定义的标识),这个错落颇有意思。android

 

 

swift代码:web

import UIKitswift

 

class ViewController: UIViewController, UIWebViewDelegate {ide

    

    @IBOutlet weak var theWebView: UIWebView!lua

    

    override func viewDidLoad() {url

        //加载本地htmlspa

        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

相关文章
相关标签/搜索