【Swift】WKWebView與JS的交互使用

1、前言  

  近日,有朋友問我關於WKWebView與JS的交互問題,可我以前一直使用的是UIWebView,也未曾作過WKWebView的交互啊!接下來你們一塊學習下WKWebView是怎麼實現原生代碼和JS交互的。2016年時候曾寫過一篇關於UIWebView與JS的交互。傳送門>>>

javascript

2、WKWebView

  • 支持更多的HTML5的特性css

  • 高達60fps滾動刷新頻率與內置手勢html

  • 與Safari相容的JavaScript引擎java

  • 在性能、穩定性方面有很大提高佔用內存更少 協議方法及功能都更細緻web

  • 可獲取加載進度等。api

3、WKWebView的代理方法

/*! @abstract The web view's navigation delegate. */ weak open var navigationDelegate: WKNavigationDelegate?
    
    /*! @abstract The web view's user interface delegate. */ weak open var uiDelegate: WKUIDelegate?

3、WKNavigationDelegate的代理方法

//判斷連接是否容許跳轉
   optional func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) //拿到響應後決定是否容許跳轉
    optional func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) //連接開始加載時調用
   optional func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) //收到服務器重定向時調用
   optional func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) //加載錯誤時調用
   optional func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) //當內容開始到達主幀時被調用(即將完成)
    optional func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) //加載完成
    optional func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) //在提交的主幀中發生錯誤時調用
    optional func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) //當webView須要響應身份驗證時調用(如需驗證服務器證書)
    optional func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) //當webView的web內容進程被終止時調用。(iOS 9.0以後)
   optional func webViewWebContentProcessDidTerminate(_ webView: WKWebView)

4、WKUIDelegate的代理方法

  用來作一些頁面上的事件,彈窗警告,提醒等。數組

//接收到警告面板
    optional func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) //接收到確認面板
   optional func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) //接收到輸入框
   optional func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void)

5、WKWebView與JS的交互使用

  首頁建立html文件,代碼以下:

<html lang="en">
    
    <head>
        <meta charset="utf-8" />
        <title>JS交互</title>
        
        <style> body { font-size:30px; text-align:center; } * { margin: 30px; padding: 0; } h1{ color: red; } button{ width: 300px; height: 50px; font-size: 30px; } </style>
        
    </head>
    <body>
        <h1>WKWebview與iOS交互</h1>
        <h2></h2>
        <button onclick="testA()">點擊alert彈框</button>
        <button onclick="testB('我是彈窗內容')">點擊alert有參彈窗</button>
        <button onclick="testConfrim()">點擊confrim彈窗</button>
        <button onclick="buttonAction()">向iOS端傳遞數據</button>
        <script type="text/javascript">
            
            //無參數函數
            function testA() { alert("我是JS中的彈窗消息"); } //有參數函數
            function testB(value) { alert(value); } function testC(value) { return value + "value"; } //接受iOS端傳過來的參數,
            function testObject(name,age) { var object = {name:name,age:age}; return object; } function testConfrim() { comfirm("肯定修改數據嗎?") } function buttonAction(){ try { <!-- js 向iOS 傳遞數據--> window.webkit.messageHandlers.getMessage.postMessage("我是js傳遞過來的數據") }catch (e) { console.log(e) } } </script>
        
   
    </body>
</html>

   一、iOS調用js中的方法進行並傳參

//案例1
self.webView?.evaluateJavaScript("testInput('123')", completionHandler: { (data , error) in print(data as Any) }) //案例2
self.webView?.evaluateJavaScript("testObject('xjf',26)", completionHandler: { (data, err) in print("\(String(describing: data)),\(String(describing: err))") })

  二、js向iOS傳遞數據

 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("\(message.name)" + "\(message.body)") // message.name 方法名 // message.body 傳遞的數據
    }

  三、在js中點擊按鈕,進行彈窗實現

//MARK:WKUIDelegate
    //此方法做爲js的alert方法接口的實現,默認彈出窗口應該只有提示消息,及一個確認按鈕,固然能夠添加更多按鈕以及其餘內容,可是並不會起到什麼做用
    //點擊確認按鈕的相應事件,須要執行completionHandler,這樣js才能繼續執行
    ////參數 message爲 js 方法 alert(<message>) 中的<message>
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertViewController = UIAlertController(title: "提示", message:message, preferredStyle: UIAlertController.Style.alert) alertViewController.addAction(UIAlertAction(title: "確認", style: UIAlertAction.Style.default, handler: { (action) in completionHandler() })) self.present(alertViewController, animated: true, completion: nil) } // confirm
    //做爲js中confirm接口的實現,須要有提示信息以及兩個相應事件, 確認及取消,而且在completionHandler中回傳相應結果,確認返回YES, 取消返回NO
    //參數 message爲 js 方法 confirm(<message>) 中的<message>
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alertVicwController = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertController.Style.alert) alertVicwController.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: { (alertAction) in completionHandler(false) })) alertVicwController.addAction(UIAlertAction(title: "肯定", style: UIAlertAction.Style.default, handler: { (alertAction) in completionHandler(true) })) self.present(alertVicwController, animated: true, completion: nil) } // prompt
    //做爲js中prompt接口的實現,默認須要有一個輸入框一個按鈕,點擊確認按鈕回傳輸入值
    //固然能夠添加多個按鈕以及多個輸入框,不過completionHandler只有一個參數,若是有多個輸入框,須要將多個輸入框中的值經過某種方式拼接成一個字符串回傳,js接收到以後再作處理
    //參數 prompt 爲 prompt(<message>, <defaultValue>);中的<message>
    //參數defaultText 爲 prompt(<message>, <defaultValue>);中的 <defaultValue>
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alertViewController = UIAlertController(title: prompt, message: "", preferredStyle: UIAlertController.Style.alert) alertViewController.addTextField { (textField) in textField.text = defaultText } alertViewController.addAction(UIAlertAction(title: "完成", style: UIAlertAction.Style.default, handler: { (alertAction) in completionHandler(alertViewController.textFields![0].text) })) self.present(alertViewController, animated: true, completion: nil) }

  四、獲取網頁中節點的數據 

//網頁加載完成
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{ //設置JS
    NSString *js = @"document.getElementsByTagName('h1')[0].innerText"; //執行JS
    [webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) { NSLog(@"value: %@ error: %@", response, error); }]; }

  五、經過注入JS修改節點的內容

let js = "document.getElementsByTagName('h2')[0].innerText = '這是一個iOS寫入的方法'"; //將js注入到網頁中

  六、js獲取DOM節點的幾種方式

document.getElementById();//id名,
document.getElementsByTagName();//標籤名
document.getElementsByClassName();//類名
document.getElementsByName();//name屬性值,通常不用
document.querySelector();//css選擇符模式,返回與該模式匹配的第一個元素,結果爲一個元素;若是沒找到匹配的元素,則返回null
document.querySelectorAll()//css選擇符模式,返回與該模式匹配的全部元素,結果爲一個類數組

 6、JavaScriptCore

  JavaScriptCore 這個庫是 Apple 在 iOS 7 以後加入到標準庫的,它對 iOS Native 與 JS 作交互調用產生了劃時代的影響。安全

   JavaScriptCore 大致是由 4 個類以及 1 個協議組成的:服務器

  • JSContext 是 JS 執行上下文,你能夠把它理解爲 JS 運行的環境。併發

  • JSValue 是對 JavaScript 值的引用,任何 JS 中的值均可以被包裝爲一個 JSValue。

  • JSManagedValue 是對 JSValue 的包裝,加入了「conditional retain」。

  • JSVirtualMachine 表示 JavaScript 執行的獨立環境。

  還有 JSExport 協議:

實現將原生類及其實例方法,類方法和屬性導出爲 JavaScript 代碼的協議。

  這裏的 JSContext,JSValue,JSManagedValue 相對比較好理解,下面咱們把 JSVirtualMachine 單拎出來講明一下:

  JSVirtualMachine 的用法和其與 JSContext 的關係

  JSVirtualMachine 實例表示用於 JavaScript 執行的獨立環境。 您使用此類有兩個主要目的:支持併發 JavaScript 執行,並管理 JavaScript 和 Objective-C 或 Swift 之間橋接的對象的內存。

  關於 JSVirtualMachine 的使用,通常狀況下咱們不用手動去建立 JSVirtualMachine。由於當咱們獲取 JSContext 時,獲取到的 JSContext 從屬於一個 JSVirtualMachine。

  每一個 JavaScript 上下文(JSContext 對象)都屬於一個 JSVirtualMachine。 每一個 JSVirtualMachine 能夠包含多個上下文,容許在上下文之間傳遞值(JSValue 對象)。 可是,每一個 JSVirtualMachine 是不一樣的,即咱們不能將一個 JSVirtualMachine 中建立的值傳遞到另外一個 JSVirtualMachine 中的上下文。

  JavaScriptCore API 是線程安全的 —— 例如,咱們能夠從任何線程建立 JSValue 對象或運行 JS 腳本 - 可是,嘗試使用相同 JSVirtualMachine 的全部其餘線程將被阻塞。 要在多個線程上同時(併發)運行 JavaScript 腳本,請爲每一個線程使用單獨的 JSVirtualMachine 實例。

7、案例源碼:

class NAHomeViewController : UIViewController,WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate,UINavigationControllerDelegate { var webView : WKWebView?
    var content : JSContext?
    var userContentController : WKUserContentController? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "首頁"
       
        //建立配置對象
        let configuration = WKWebViewConfiguration() //爲WKWebViewController設置偏好設置
        let preference = WKPreferences() configuration.preferences = preference //容許native與js交互
        preference.javaScriptEnabled = true

        //初識化webView
        let webView = WKWebView.init(frame: CGRect(x: 0, y: 64, width: self.view.frame.size.width, height: 300)) let path = Bundle.main.path(forResource: "wKWebView", ofType: "html") webView.navigationDelegate = self webView.uiDelegate = self let request = URLRequest.init(url: URL.init(fileURLWithPath: path!)) webView.load(request) self.view.addSubview(webView) self.webView = webView let userContentController = WKUserContentController() configuration.userContentController = userContentController userContentController.add(self,name: "getMessage") self.userContentController = userContentController let btn = UIButton.init(frame: CGRect(x: 100, y: 390, width: 100, height: 50)) btn.setTitleColor(.black, for: .normal) btn.setTitle("oc調用js", for: .normal) btn.addTarget(self, action: #selector(btnAction), for: .touchUpInside) self.view.addSubview(btn) self.view.backgroundColor = .white } @objc func btnAction() { self.webView?.evaluateJavaScript("testInput('123')", completionHandler: { (data , error) in print(data as Any) }) self.webView?.evaluateJavaScript("testObject('xjf',26)", completionHandler: { (data, err) in print("\(String(describing: data)),\(String(describing: err))") }) } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("\(message.name)" + "\(message.body)") // message.name 方法名 // message.body 傳遞的數據
 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.
 } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // webView.evaluateJavaScript("testA()") { (data, err) in // print("\(String(describing: data)),\(String(describing: err))") // }
 } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("\(error)") } //MARK:WKUIDelegate
    //此方法做爲js的alert方法接口的實現,默認彈出窗口應該只有提示消息,及一個確認按鈕,固然能夠添加更多按鈕以及其餘內容,可是並不會起到什麼做用
    //點擊確認按鈕的相應事件,須要執行completionHandler,這樣js才能繼續執行
    ////參數 message爲 js 方法 alert(<message>) 中的<message>
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertViewController = UIAlertController(title: "提示", message:message, preferredStyle: UIAlertController.Style.alert) alertViewController.addAction(UIAlertAction(title: "確認", style: UIAlertAction.Style.default, handler: { (action) in completionHandler() })) self.present(alertViewController, animated: true, completion: nil) } // confirm
    //做爲js中confirm接口的實現,須要有提示信息以及兩個相應事件, 確認及取消,而且在completionHandler中回傳相應結果,確認返回YES, 取消返回NO
    //參數 message爲 js 方法 confirm(<message>) 中的<message>
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alertVicwController = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertController.Style.alert) alertVicwController.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: { (alertAction) in completionHandler(false) })) alertVicwController.addAction(UIAlertAction(title: "肯定", style: UIAlertAction.Style.default, handler: { (alertAction) in completionHandler(true) })) self.present(alertVicwController, animated: true, completion: nil) } // prompt
    //做爲js中prompt接口的實現,默認須要有一個輸入框一個按鈕,點擊確認按鈕回傳輸入值
    //固然能夠添加多個按鈕以及多個輸入框,不過completionHandler只有一個參數,若是有多個輸入框,須要將多個輸入框中的值經過某種方式拼接成一個字符串回傳,js接收到以後再作處理
    //參數 prompt 爲 prompt(<message>, <defaultValue>);中的<message>
    //參數defaultText 爲 prompt(<message>, <defaultValue>);中的 <defaultValue>
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alertViewController = UIAlertController(title: prompt, message: "", preferredStyle: UIAlertController.Style.alert) alertViewController.addTextField { (textField) in textField.text = defaultText } alertViewController.addAction(UIAlertAction(title: "完成", style: UIAlertAction.Style.default, handler: { (alertAction) in completionHandler(alertViewController.textFields![0].text) })) self.present(alertViewController, animated: true, completion: nil) } }

 

   參考鏈接:https://mp.weixin.qq.com/s/Tp7WxHXp_0EATIKvSuBhlw

相關文章
相關標籤/搜索