美文网首页
(WKWebView) - 禁止长按交互

(WKWebView) - 禁止长按交互

作者: 粒粒皇 | 来源:发表于2019-08-26 11:29 被阅读0次

    使用WKWebView展示html文章,loadFileURL加载html文件,加载本地缓存图片。长按图片会弹窗,长按文字弹窗,点击链接跳转。。。

    • 1.禁止长按交互
    let configuration = WKWebViewConfiguration()
    configuration.preferences = WKPreferences()
    configuration.preferences.minimumFontSize = 12
    configuration.preferences.javaScriptEnabled = true
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
    
    // "document.documentElement.style.webkitTouchCallout='none';" // 禁止长按
    // "document.documentElement.style.webkitUserSelect='none';" // 禁止选择
    let javascript = "document.documentElement.style.webkitTouchCallout='none';document.documentElement.style.webkitUserSelect='none';"
    let noneSelectScript = WKUserScript(source: javascript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
    
    let v = WKWebView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: contentHeight), configuration: configuration)
    v.configuration.userContentController.addUserScript(noneSelectScript)
    

    当然也可以这样

    webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';", completionHandler: nil)
    webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none';", completionHandler: nil)
    

    还可以这样

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         print("加载完成")
    
         // 禁止长按/选择
         webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';", completionHandler: nil)
         webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none';", completionHandler: nil)
    }
    
    • 2.禁止链接跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
         DLog("navigationAction = %@, request = %@", navigationAction, navigationAction.request.url ?? "url = nil")
    
         // 禁止链接跳转
         if navigationAction.request.url?.scheme?.contains("http") == true {
            decisionHandler(WKNavigationActionPolicy.cancel)
         } else {
            decisionHandler(WKNavigationActionPolicy.allow)
         }
    }
    

    相关文章

      网友评论

          本文标题:(WKWebView) - 禁止长按交互

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