iOS WKWebView與JS交互

1.1 WKScriptMessageHandler協(xié)議

WKScriptMessageHandler其實就是一個遵循的協(xié)議,它能讓網(wǎng)頁通過JS把消息發(fā)送給OC。其中協(xié)議方法。

/*! @abstract Invoked when a script message is received from a webpage.
 @param userContentController The user content controller invoking the
 delegate method.
 @param message The script message received.
 */
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;

從協(xié)議中我們可以看出這里使用了兩個類WKUserContentController和WKScriptMessage。WKUserContentController可以理解為調(diào)度器,WKScriptMessage則是攜帶的數(shù)據(jù)。

1.2 WKUserContentController

WKUserContentController有兩個核心方法,也是它的核心功能。

- (void)addUserScript:(WKUserScript *)userScript;: js注入,即向網(wǎng)頁中注入我們的js方法,這是一個非常強大的功能,開發(fā)中要慎用。
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;:添加供js調(diào)用oc的橋梁。這里的name對應(yīng)WKScriptMessage中的name,多數(shù)情況下我們認(rèn)為它就是方法名。

1.3 WKScriptMessage

WKScriptMessage就是js通知oc的數(shù)據(jù)。其中有兩個核心屬性用的很多。

@property (nonatomic, readonly, copy) NSString *name; :對應(yīng)- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;添加的name。
@property (nonatomic, readonly, copy) id body;:攜帶的核心數(shù)據(jù)。

js調(diào)用時只需

window.webkit.messageHandlers.<name>.postMessage(<messageBody>)

這里的name就是我們添加的name。

一、JS調(diào)OC代碼

JS代碼:

<!DOCTYPE html>
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
<body style="background-color: white;">
    <script type="text/javascript">
        function jsCallNative() {
           window.webkit.messageHandlers.callNativeAndSend.postMessage('callcallcall');
           alert(callNative);
        }
    </script>
    
    <button type="button" onclick = "jsCallNative()" style="width:100%; height:30px;"/>調(diào)用OC代碼</button>
</body>
</html>

注意:window.webkit.messageHandlers.callNativeAndSend.postMessage('callcallcall');這行代碼才是調(diào)用oc的方法,方法名:callNativeAndSend 參數(shù)就是:callcallcall

OC代碼:

 WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:@"callNativeAndSend"];
        [userContentController addScriptMessageHandler:self name:@"NativeObject.shareString"];
        // WKWebView的配置
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController   = userContentController;
        //創(chuàng)建WKWebView
        
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) configuration:configuration];

上面代碼,是創(chuàng)建webView,并且告訴JS有哪些方法。

Adding a script message handler with name name causes the JavaScript function window.webkit.messageHandlers.name.postMessage(messageBody) to be defined in all frames in all web views that use the user content controller.
譯:添加名稱名稱的腳本消息處理程序會導(dǎo)致在所有使用用戶內(nèi)容控制器的Web視圖的所有框架中定義JavaScript函數(shù)window.webkit.messageHandlers.name.postMessage(messageBody)。

- (void)addScriptMessageHandler:(id<WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;

但是 [userContentController addScriptMessageHandler:self name:@"NativeObject.shareString"];親測是無效的,其只能像[userContentController addScriptMessageHandler:self name:@"callNativeAndSend"];添加這種。

當(dāng)JS調(diào)用OC方法后,會執(zhí)行以下回調(diào),name是方法名,可以用其作區(qū)分判斷,body是參數(shù)

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"\n body:%@ \n name:%@",message.body,message.name);
}

另外還有一種注入JS的方式:

- (void)addUserScript:(WKUserScript *)userScript;: js注入,即向網(wǎng)頁中注入我們的js方法,這是一個非常強大的功能,開發(fā)中要慎用。

注意:在UIWebview中,當(dāng)我們第一次給h5注入js方法后,在后續(xù)的頁面操作過程中可能會丟失這個方法,也就是js不再能拿到這個方法??赡茉蚴牵涸趆5頁面操作過程中,創(chuàng)建了兩個window,而我們加的js方法仍在第一個window上,在新的window上就拿不到了。在WKWebview中,丟失方法是因為js調(diào)用方法調(diào)早了,而我們還沒有注入;js延遲調(diào)用問題不存在了。 在WKWebview中用上述方式注入代碼后會避免此問題出現(xiàn)?。?!*

二、OC調(diào)JS代碼

[webView evaluateJavaScript:@"globalObject.nativeCallJS('abc')" completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        if (error) {
            NSLog(@"error:%@",error);
        }
    }];

abc是傳遞給JS的參數(shù),globalObject是JS中全局屬性,nativeCallJS是其下的方法。

三、優(yōu)化

[userContentController addScriptMessageHandler:self name:@"callNativeAndSend"]
當(dāng)我們添加注入方法時,以上代碼會強引用self,即當(dāng)前控制器,會導(dǎo)致再dealloc的時候self不會釋放,解決辦法是創(chuàng)建一個新類,并實現(xiàn)WKScriptMessageHandler代理方法。代碼如下:

WeakScriptMessageDelegate.h
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>

@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>

@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end
WeakScriptMessageDelegate.m

#import "WeakScriptMessageDelegate.h"

@implementation WeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate
{
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}

@end

盡管如此,在self里還是要在dealloc的時候移除方法:

[[_wkWebView configuration].userContentController removeScriptMessageHandlerForName:@"jsCallNative"];

執(zhí)行上述代碼之后,self和WeakScriptMessageDelegate都能安全釋放。

推薦一個強大的蘋果官方庫,JavaScriptCore 以及 iOS JavaScriptCore使用。

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

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

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