美文网首页
iOS WKWebView-IOS与JS交互

iOS WKWebView-IOS与JS交互

作者: 汤姆杰瑞 | 来源:发表于2020-12-17 16:06 被阅读0次
//WKWebView相关代理
<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
//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交互

      本文链接:https://www.haomeiwen.com/subject/xsuzgktx.html