WKwebview 与原生交互

代理实现<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 这个发消息

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容