关于iOS与JS交互

以WKWebView为例

监听JS方法: - (void)addScriptMessageHandler:(id )scriptMessageHandler name:(NSString *)name;

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *controller = [[WKUserContentController alloc] init];
    //监听的JS  @"goMsPage"为监听JS方法
    [controller addScriptMessageHandler:self name:@"goMsPage"];
    configuration.userContentController = controller;
    WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configuration];

代理需要实现方法处理事件:- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"goMsPage"]) {
        //处理事件
    }
}

还有很关键的一点

  • JS的实现必须为 window.webkit.messageHandlers.goMsPage.postMessage(""); 如果你家Android没问题你监听不到就让你家前段适配一下吧。

iOS调用JS方法:- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;

[webView evaluateJavaScript:@"appback('string')" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
                
 }];

你可能感兴趣的:(关于iOS与JS交互)