iOS WKWebView与JS交互

6,190 阅读3分钟

1.1 WKScriptMessageHandler协议

WKScriptMessageHandler其实就是一个遵循的协议,它能让网页通过JS把消息发送给OC。其中协议方法。

/*! @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;

从协议中我们可以看出这里使用了两个类WKUserContentController和WKScriptMessage。WKUserContentController可以理解为调度器,WKScriptMessage则是携带的数据。

1.2 WKUserContentController

WKUserContentController有两个核心方法,也是它的核心功能。

- (void)addUserScript:(WKUserScript *)userScript;: js注入,即向网页中注入我们的js方法,这是一个非常强大的功能,开发中要慎用。
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;:添加供js调用oc的桥梁。这里的name对应WKScriptMessage中的name,多数情况下我们认为它就是方法名。

1.3 WKScriptMessage

WKScriptMessage就是js通知oc的数据。其中有两个核心属性用的很多。

@property (nonatomic, readonly, copy) NSString *name; :对应- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;添加的name。
@property (nonatomic, readonly, copy) id body;:携带的核心数据。

js调用时只需

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

这里的name就是我们添加的name。

一、JS调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;"/>调用OC代码</button>
</body>
</html>

注意:window.webkit.messageHandlers.callNativeAndSend.postMessage('callcallcall');这行代码才是调用oc的方法,方法名:callNativeAndSend 参数就是: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;
        //创建WKWebView
        
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) configuration:configuration];

上面代码,是创建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. 译:添加名称名称的脚本消息处理程序会导致在所有使用用户内容控制器的Web视图的所有框架中定义JavaScript函数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"];添加这种。

当JS调用OC方法后,会执行以下回调,name是方法名,可以用其作区分判断,body是参数

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

另外还有一种注入JS的方式:

- (void)addUserScript:(WKUserScript *)userScript;: js注入,即向网页中注入我们的js方法,这是一个非常强大的功能,开发中要慎用。

注意:在UIWebview中,当我们第一次给h5注入js方法后,在后续的页面操作过程中可能会丢失这个方法,也就是js不再能拿到这个方法。可能原因是:在h5页面操作过程中,创建了两个window,而我们加的js方法仍在第一个window上,在新的window上就拿不到了。在WKWebview中,丢失方法是因为js调用方法调早了,而我们还没有注入;js延迟调用问题不存在了。 在WKWebview中用上述方式注入代码后会避免此问题出现!!!*

二、OC调JS代码

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

abc是传递给JS的参数,globalObject是JS中全局属性,nativeCallJS是其下的方法。

###三、优化 [userContentController addScriptMessageHandler:self name:@"callNativeAndSend"] 当我们添加注入方法时,以上代码会强引用self,即当前控制器,会导致再dealloc的时候self不会释放,解决办法是创建一个新类,并实现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"];

执行上述代码之后,self和WeakScriptMessageDelegate都能安全释放。

推荐一个强大的苹果官方库,JavaScriptCore 以及 iOS JavaScriptCore使用