WKWebView与js 交互

1,先说 uiwebview与 js 交互

@property (nonatomic, strong, readonly) JSContext    *jsContext;
        _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
 // 2. 关联打印异常
        _jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
            context.exception = exceptionValue;
            NSLog(@"异常信息:%@", exceptionValue);
        };
 _jsContext[@"museum"] = ^(NSDictionary *param) {
//做自己的操作            
NSLog(@"%@", param);            
        };

2,WKWebView与js 交互

 WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    [configuration.userContentController addScriptMessageHandler:self name:@"callbackFunc"];    
    mainWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) configuration:configuration];
    mainWebView.backgroundColor = [UIColor whiteColor];
    mainWebView.UIDelegate = self;
    mainWebView.navigationDelegate = self;
    mainWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:mainWebView];
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message
{
     __weak __typeof(self)weakSelf = self;
    if ([message.name isEqualToString:@"callbackFunc"])
    {
       //如果需要多个值是 message.body 是一个NSArray
        NSLog(@"%@", message.body);
    }
}

你可能感兴趣的:(WKWebView与js 交互)