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);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容