iOS WKWebView的JS適配HTML(HTML不需要改動)

前言

當你的項目需要從UIWebView換成WKWebView時,或許會煩惱HTML那邊需要修改JS交互部分,但是以下將會告訴你,其實HTML并不需要修改任何代碼,而且iOS這邊改動也非常簡單。


首先假設HTML原本的JavaScript交互代碼如下

//JS代碼 - 1
if (window.jSBridgeInstance && window.jSBridgeInstance.sendMessage) {
    var act = "Action";
    var jsonDict = {
                      "imagUrl": "", 
                      "title": "積分商城", 
                      "login": "0"
                   };
    window.jSBridgeInstance.sendMessage(act, jsonDict);
}

如果要改HTML端的話,需要修改如下(但是我們不改HTML,我們改iOS端代碼)

//JS代碼 - 2
//如果修改HTML的JS代碼,則iOS不需要修改
if (window.webkit && window.webkit.messageHandlers) {
    var act = "Action";
    var jsonDict = {
                      "act" : act,
                      "imagUrl": "", 
                      "title": "積分商城", 
                      "login": "0"
                   };
    //注意,iOS的postMessage方法只接收一個參數(shù),如果傳多個參數(shù),那么WKScriptMessage的body只接收到第一個參數(shù)
    window.webkit.messageHandlers.callTemplate.postMessage(jsonDict);
}

iOS 端修改如下(本篇文章的重點)

  • OC代碼
//iOS 代碼 - 1
//如果修改iOS代碼,則JS代碼不需要修改
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
[config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"callTemplate"];
NSString *scriptSource = @"\
   window.jSBridgeInstance = window.webkit.messageHandlers.callTemplate;\
   window.jSBridgeInstance.sendMessage = function(act, json) {\
       var jsonDict = {\
           \"key1\": act,\
           \"key2\": json\
       };\
       window.webkit.messageHandlers.callTemplate.postMessage(jsonDict);\
   }";
WKUserScript *script = [[WKUserScript alloc] initWithSource:scriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:false];
[config.userContentController addUserScript:script];
_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
  • Swift代碼
//iOS 代碼 - 2
//如果修改iOS代碼,則JS代碼不需要修改
let config: WKWebViewConfiguration = WKWebViewConfiguration();
config.userContentController.add(WeakScriptMessageDelegate.initWith(self), name: "callTemplate");
let scriptSource: String = """
       window.jSBridgeInstance = window.webkit.messageHandlers.callTemplate;
       window.jSBridgeInstance.sendMessage = function(act, json) {
               var jsonDict = {
                   "key1": act,
                   "key2": json
               };
               window.webkit.messageHandlers.callTemplate.postMessage(jsonDict);
       }
 """;
let script:WKUserScript = WKUserScript.init(source: scriptSource, injectionTime: .atDocumentStart, forMainFrameOnly: false);
config.userContentController.addUserScript(script);
webView = WKWebView.init(frame: self.view.bounds, configuration: config);

注:
①第二行callTemplate可以隨意命名,假如你命名為x,那么對應的scriptSource里邊的callTemplate也都修改為x。
② scriptSource中jSBridgeInstance和sendMessage看你們的HTML的JS代碼而定。
③如果原來的HTML的JS有三個參數(shù),那么修改如下:

NSString *scriptSource = @"\
   window.jSBridgeInstance = window.webkit.messageHandlers.callTemplate;\
   window.jSBridgeInstance.sendMessage = function(param1, param2, param3) {\
       var jsonDict = {\
           \"key1\": param1,\
           \"key2\": param2,\
           \"key3\": param3,\
       };\
       window.webkit.messageHandlers.callTemplate.postMessage(jsonDict);\
   }";

更多參數(shù)時以此類推。

代碼例子下載


后言

很慶幸學了HTML、CSS和JS,一開始什么是JS都不懂,那時候說什么JS交互,也只是會網(wǎng)上搜索一下資料,照葫蘆畫瓢。昨天在用Qt做WebView部分時,有所感悟,在下班回來的路上,突發(fā)奇想iOS是不是也可以稍微靈活一點,而不必web那邊做修改呢,于是便進行了嘗試,這篇文章便是成果。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容