iOS與JS交互之WKWebView-WKScriptMessageHandler協議


前言
  “iOS與JS交互”。iOS指iOS原生代碼(文章只有OC示例),JS指WEB前端(不單指JavaScript),交互指JS調用iOSiOS調用JS。將iOS與JS交互總結成了6種方式,並將逐一介紹。
目錄如下:
本文介紹如果使用WKWebView的WKScriptMessageHandler實現iOS與JS交互。
WKWebView是Apple在iOS8推出的Webkit框架中的負責網頁的渲染與展示的類,相比UIWebView速度更快,占用內存更少,支持更多的HTML特性。WKScriptMessageHandler是WebKit提供的一種在WKWebView上進行JS消息控制的協議。
一、JS調用iOS:
  • 實現邏輯:點擊JS的登錄按鈕,JS將登錄成功后的token數據傳遞給iOS,iOS將收到的數據展示出來。

  • 實現效果:


     
    JS調用iOS實現效果
  • JS代碼:

//! 登錄按鈕
<button onclick = "login()" style = "font-size: 18px;">登錄</button>
//! 登錄
function login() {
  var token = "js_tokenString";
  loginSucceed(token);
}

//! 登錄成功
function loginSucceed(token) {
  var action = "loginSucceed";
  window.webkit.messageHandlers.jsToOc.postMessage(action, token);
}
  • iOS代碼:
//! 導入WebKit框架頭文件
#import <WebKit/WebKit.h>

//! WKWebViewWKScriptMessageHandlerController遵守WKScriptMessageHandler協議
@interface WKWebViewWKScriptMessageHandlerController () <WKScriptMessageHandler>


//! 為userContentController添加ScriptMessageHandler,並指明name WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [userContentController addScriptMessageHandler:self name:@"jsToOc"]; //! 使用添加了ScriptMessageHandler的userContentController配置configuration WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.userContentController = userContentController; //! 使用configuration對象初始化webView _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
#pragma mark - WKScriptMessageHandler
//! WKWebView收到ScriptMessage時回調此方法 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name caseInsensitiveCompare:@"jsToOc"] == NSOrderedSame) { [WKWebViewWKScriptMessageHandlerController showAlertWithTitle:message.name message:message.body cancelHandler:nil]; } }
  • 實現原理:
    1、JS與iOS約定好jsToOc方法,用作JS在調用iOS時的方法;
    2、iOS使用WKUserContentController-addScriptMessageHandler:name:方法監聽namejsToOc的消息;
    3、JS通過window.webkit.messageHandlers.jsToOc.postMessage()的方式對jsToOc方法發送消息;
    4、iOS在-userContentController:didReceiveScriptMessage:方法中讀取namejsToOc的消息數據message.body

PS[userContentController addScriptMessageHandler:self name:@"jsToOc"]會引起循環引用問題。一般來說,在合適的時機removeScriptMessageHandler可以解決此問題。比如:在-viewWillAppear:方法中執行add操作,在-viewWillDisappear:方法中執行remove操作。如下:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_webView.configuration.userContentController addScriptMessageHandler:self name:@"jsToOc"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"jsToOc"];
}

 


二、iOS調用JS:

iOS調用JS方式與上篇文章一致,都是通過WKWebView的-evaluateJavaScript:completionHandler:方法來實現的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM