iOS技术点iOSiOS Developer

iOS WKWebview 禁止长按(超链接、图片、文本...)

2017-03-10  本文已影响3554人  生气龙
选中样式

what the ..... 这不是我们要的效果~


最近公司要命的催进度,大家决定后面采用web,其实我内心是不愿意的,志愿于美方共建Native美好家园

这些让人看起来渣到爆的网页效果.. 一定要搞掉 对于苹果爸爸的新WKWebview来说UiWebview的解决方案并不完全受用, 在WKWebview头文件翻来翻去 没有找到 可以关闭。不过我在配置信息 WKWebViewConfiguration 的头文件里找到了这个我们可以添加些自己的脚本

/*! @abstract Adds a user script.
 @param userScript The user script to add.
*/
- (void)addUserScript:(WKUserScript *)userScript;

我们可以添加些脚本到这个用户配置中,这启发了我

- (WKWebView *)webView{
    if (!_webView) {
        //创建WKWebview配置对象
        WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc] init];
        config.preferences = [[WKPreferences alloc] init];
        config.preferences.minimumFontSize =10;
        config.preferences.javaScriptEnabled =YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically =NO;

        NSMutableString *javascript = [NSMutableString string];
        [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
        [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
        WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        //创建webView
        WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds configuration:config];
        [webView.configuration.userContentController addUserScript:noneSelectScript];
        webView.UIDelegate = self;
        webView.navigationDelegate = self;
        webView.backgroundColor = [UIColor whiteColor];
        webView.scrollView.scrollEnabled = YES;
        [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        _webView = webView;

    }
    return _webView;
}

也可以直接执行JS , 这样的话要等载入完成后再执行

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
}

SO..搞定 刚开心了一小会,把弄了下 长按图片又弹出了这个 还有路径,我去


超链接弹出的对话框

搜了半天博客没有解决方案,去stack overflow上碰碰运气,原来苹果会在html中对herf关键字 做优化,即使你href="#" 或 href="void(0)" 都会触发对话框
所以,两种解决方案
1 在html标签里 彻底删除href=xx

2 如果你业务逻辑需要的话,不妨加个标签代替href

a .originalLink { color: blue; text-decoration: underline; cursor: pointer; }
<a class="originalLink" onclick="location.href='http://mylink';">Real URL Link</a>

参考文章:
http://stackoverflow.com/questions/12304012/preventing-default-context-menu-on-longpress-longclick-in-mobile-safari-ipad
http://blog.csdn.net/shaobo8910/article/details/53485937
http://www.mamicode.com/info-detail-503121.html

上一篇 下一篇

猜你喜欢

热点阅读