欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WKWebView与js 交互

程序员文章站 2024-03-01 09:06:04
...

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