1.js给webview发消息
js重定向时可以发给我们一个标识。在我们的代码中实现webview代理方法,每一次加载webview都会实现这个方法
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
if let schema = request.URL?.scheme{
//如果不需要接收参数,那么收到这个标识时就可以去实现自己的本地功能
if schema.caseInsensitiveCompare("aaa") == NSComparisonResult.OrderedSame{
//自己要实现的
}
//如果要接收参数,js可以将参数直接跟在url后面
else if schema.caseInsensitiveCompare("bbb") == NSComparisonResult.OrderedSame{
//自定义参数分隔字符
if let url:String = request.URL!.absoluteString{
let urlComponents: [String] = url.componentsSeparatedByString("..")
print(urlComponents)
}
//自己要实现的
}
}
reture true
}
2.webview调用js
假设js的方法名:jsFunction()
//不需要传參
let js = "jsFunction()"
//需要传參
let js = "jsFunction("parameter")"
self.webView?.stringByEvaluatingJavaScriptFromString(js)