在使用 WKWebView 展示 H5 时,如果 H5 中有图片,长按图片会出现弹框,在 iOS11 系统中,存储图像,如果未开启相册权限,会直接 Crash 掉:
解决方案一(原生解决):
在代理方法中添加如下代码,禁掉弹框:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { NSLog(@"webViewDidFinishLoad"); [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil]; [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil]; }
另一种:
// 禁止选择CSS NSString *css = @"body{-webkit-user-select:none;-webkit-user-drag:none;}"; // CSS选中样式取消 NSMutableString *javascript = [NSMutableString string]; [javascript appendString:@"var style = document.createElement('style');"]; [javascript appendString:@"style.type = 'text/css';"]; [javascript appendFormat:@"var cssContent = document.createTextNode('%@');", css]; [javascript appendString:@"style.appendChild(cssContent);"]; [javascript appendString:@"document.body.appendChild(style);"]; // javascript注入 WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [userContentController addUserScript:noneSelectScript]; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.userContentController = userContentController; CGRect frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44.f -20.f); WKWebView *webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration]; NSURLRequest* request = [NSURLRequest requestWithURL:_brandInfoURL]; [webView loadRequest:request]; _webView = webView; [self.view addSubview:webView];
解决方案二(H5)解决:
img { pointer-events: none; }