iOS WKWebView与JS交互

假设JS的交互代码是

//content为Android WebView需要获取到的数据,多个用,隔开,如果不需要传值{}也要加,window.webkit.messageHandlers.openCop.postMessage只有openCop是可以修改的名称其他是固定写法
window.webkit.messageHandlers.openCop.postMessage({content});

那么iOS WKWebView界面只需要:

需要加入delegate
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //对JS调用的方法进行监听,最好集中处理
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"openCop"];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //移除监听,不移除一定会报错
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"openCop"];
}

//用来接收js调用本地方法的拦截器
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSDictionary * dic = message.body;
    if ([message.name isEqualToString:@"openCop"]) { 
        
    } 
}

你可能感兴趣的:(iOS,HTML,iOS,UIWebView)