Reference: https://00red.com/blog/2016/03/22/teacher-swift-uiwebview-javascript/
1. JS triggers SWIFT
Swift Code
import UIKit import JavaScriptCore class ViewController: UIViewController,UIWebViewDelegate { var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let path = Bundle.main.path(forResource: "test", ofType: "html") let url = NSURL(fileURLWithPath: path!) let request = NSURLRequest(url: url as URL) webView = UIWebView(frame: self.view.frame) webView.loadRequest(request as URLRequest) self.view.addSubview(webView); // let jsContext = self.webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext jsContext?.setObject(JavaScriptMethod(), forKeyedSubscript: "callSwift" as (NSCopying & NSObjectProtocol)!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //must add the preceding @objc @objc protocol JavaScriptMethodProtocol: JSExport { //The parameter must be preceded by an _underscore func postContent(_ value: String, _ number: String) func postContent2(_ value: String) } class JavaScriptMethod : NSObject, JavaScriptMethodProtocol { func postContent(_ value: String, _ number: String) { //method name postContent print("dd"+value); } func postContent2(_ value: String){ print("str:"+value); } }
test.html
<html> <meta charset="utf-8" /> <body> <BR><BR> <button onclick='callSwift.postContent("我是value1", 2)'>Call Swift</button> <button onclick='callSwift.postContent2("I am a string")'>Call Swift2</button> </body> </html>
html and SWIFT files in the same directory
2 : The second form of notification via message
swift first
import UIKit import Foundation import JavaScriptCore import WebKit; class Page1: UIViewController,WKScriptMessageHandler{ override func viewDidLoad() { super.viewDidLoad() let conf = WKWebViewConfiguration() conf.userContentController.add(self as! WKScriptMessageHandler, name: "NOTIFY") let web = WKWebView(frame: self.view.frame, configuration: conf) self.view.addSubview(web) let url:String = "http://192.168.2.188/9/2.php" web.load(NSURLRequest(url: NSURL(string: url) as! URL) as URLRequest); } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "NOTIFY" { if let dic = message.body as? NSDictionary { print(dic["link"]) print(dic["image"]) } } } }
Then the JS in the php file is triggered by the following JS code
var data = {}; data.link = "aaa"; data.image = "iiiii"; webkit.messageHandlers.NOTIFY.postMessage(data);
2. Swift triggers js
Add JS code to the above html
<script type="text/javascript"> function doFun(str){ alert(str); } </script>
Add the code above in swift
self.webView.stringByEvaluatingJavaScript(from: "doFun('你执行了DOFUN')")
其中 执行JS 代码 需要等HTML 加载完,可通过代理监控事件判断
另: 如果存在 300毫秒点击延迟可 改用 WKWebView 并 在html 的meta 中设置 user-scalable=0
** swift 通过执行 js 返回 执行 结果 ,比如 通过JS 的方法 获取页面的title
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { //要执行的js 语句 let script:String = "document.title"; webView.evaluateJavaScript(script, completionHandler: { (result, error) in if result != nil { print("通过evaluateJavaScript获取的结果:"+(result as! String)); //结果就是打印出了该站的title 不过是通过js 的方法 } else { print(error ?? "Error") } }) }
相关参考: 根据某个标签的属性值获取另外一个属性值
http://mft.iteye.com/admin/blogs/2378327