\(^o^)/~ 与H5交互WKWebView原生

   //使用配置文件
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 默认为0
    config.preferences.minimumFontSize = 3;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    //不通过用户交互,是否可以打开窗口
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
  //信息传递 name:    postMessage前关键字         window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});

  //发布
    [config.userContentController addScriptMessageHandler:self name:@"releasePaper"];
//创建WK
 _wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    _wkWebView.navigationDelegate = self;
    [self.view addSubview:_wkWebView];
    
    
      [_wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    NSURL * url;
    if (![self.urlStr hasPrefix:@"http"]) {
        url = [NSURL URLWithString:[self.urlStr stringByAppendingPathComponent:self.urlStr]];
    } else {
        url = [NSURL URLWithString:self.urlStr];
    }
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.wkWebView loadRequest:request];

WKScriptMessageHandler实现代理

#pragma mark - WKScriptMessageHandler
// 从web界面中接收到一个脚本时调用

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"JS函数执行 %@",NSStringFromSelector(_cmd));
NSLog(@"%@",message.body);
//收到的信息
  //    id body = message.body;


//返回首页
if ([message.name isEqualToString:@"releasePaper"])
{
 
  [self.navigationController popToRootViewControllerAnimated:YES];
}
}
        ///WKWebView本身提供一个方法进行处理JS代码.
      //javaScriptString:所执行的JS代码
  - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;

{

}
  //在JS端调用alert函数时,会触发此代理方法。
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;
{

}
//JS端调用confirm函数时,会触发此代理方法。
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;
{

}
//JS端调用prompt函数时,会触发此代理方法。
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
{

}

你可能感兴趣的:(\(^o^)/~ 与H5交互WKWebView原生)