美文网首页
WKwebview 与原生交互

WKwebview 与原生交互

作者: 开创Me世界 | 来源:发表于2021-11-16 14:10 被阅读0次

代理实现<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>

代理注册viewWillAppear方法里

[self.MyWKWebView.configuration.userContentController addScriptMessageHandler:self name:@"first"];

代理移除viewWillDisappear方法里

[self.MyWKWebView.configuration.userContentController removeScriptMessageHandlerForName:@"first"];

WKwebview 内部设置

  WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

        config.userContentController = [[WKUserContentController alloc] init];

        //在创建wkWebView时,需要将被js调用的方法注册进去,oc与js端对应实现

        NSString *js = @" $('meta[name=description]').remove(); $('head').append( '' );";

        WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];

        NSMutableString *javascript = [NSMutableString string];

        [javascriptappendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按

        WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

        [config.userContentController addUserScript:script];

        [config.userContentControlleraddUserScript:noneSelectScript];

        [config.userContentController addScriptMessageHandler:self name:@"first"];

        config.preferences = [[WKPreferences alloc] init];

        config.preferences.minimumFontSize = 10;

        config.preferences.javaScriptEnabled = YES;

        config.preferences.javaScriptCanOpenWindowsAutomatically = YES;

        config.allowsInlineMediaPlayback = true;

Hand 代理

#pragma mark-

#pragma mark - 👉 WKScriptMessageHandler 👈

- (void)userContentController:(WKUserContentController*)userContentControllerdidReceiveScriptMessage:(WKScriptMessage*)message {

if ([message.name isEqualToString:@"first"]) {//分享}

}

前端丢消息方法

iOS ,用window.webkit.messageHandlers.webCallShare.postMessage 这个发消息

相关文章

网友评论

      本文标题:WKwebview 与原生交互

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