iOS WKWebView-IOS与JS交互

//WKWebView相关代理

//WKUserContentController 属性
WKUserContentController* userContentController;


//配置环境
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
userContentController =[[WKUserContentController alloc]init];
[userContentController addScriptMessageHandler:self name:@"前端的web点击事件方法"];

configuration.userContentController = userContentController;
WKWebView *wkWebView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configuration];
wkWebView.UIDelegate = self;
wkWebView.scrollView.showsHorizontalScrollIndicator = NO;
wkWebView.scrollView.showsVerticalScrollIndicator = NO;
wkWebView.navigationDelegate = self;
[self.view addSubview:wkWebView];
[wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view);
 }];

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

    if ([message.name isEqualToString:@"前端的web点击事件方法"]) {
        //这里处理前端给你的相关信息比如邀请链接,或者点击前端的按钮交互
            message.body[@"url"];
        }
}

//移除WKUserContentController
- (void)dealloc
{
       [userContentController removeScriptMessageHandlerForName:@"前端的web点击事件方法"];
}

你可能感兴趣的:(iOS WKWebView-IOS与JS交互)