如何覆盖wkwebview超链接操作表

时间:2015-12-14 19:45:43

标签: ios swift

当您长按WkWebview中的超链接时,您会看到一个操作表。我希望在长按时使用我自己的一组选项覆盖该操作表,否则表现正常。我可以参加长时间的新闻活动,但我不知道如何:

  1. 阻止显示
  2. 的默认操作表
  3. 防止webview在长按结束时导航到URL。
  4. 获取webview直接指向的底层href URL或html标记本身以及相关属性(如ID)。

2 个答案:

答案 0 :(得分:3)

取消操作表的一种简单(但根本)的方法是覆盖 您应用的根视图控制器中的presentViewController:animated:completion:

Swift 3样本

override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {

  guard let alertController = viewControllerToPresent as? UIAlertController,
  alertController.preferredStyle == .actionSheet else {
    // Not an alert controller, present normally
    super.present(viewControllerToPresent, animated: flag, completion: completion)
    return    
  }

  // Create and open your own custom alert sheet
  let customAlertController = UIAlertController(...)
  super.present(customAlertController, animated: flag, completion: completion)
}

您可以从alertController.title检索链接的网址,如果您需要检索其他属性,我建议您查看Firefox的this commit,它使用JS脚本处理程序查找点击的元素并将其属性发送回应用程序。

此外,您还需要编写一些逻辑来防止取消除应用程序可能使用的WKWebView之外的任何其他警报表。

答案 1 :(得分:1)

这是覆盖菜单的有效解决方案。我仍然希望得到一些HTML属性,但还不知道如何做到这一点。

override func loadView() {
    super.loadView()

    let contentController = WKUserContentController();
    let userScript = WKUserScript(
        source: "redHeader()",
        injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
        forMainFrameOnly: true
    )
    contentController.addUserScript(userScript)
    contentController.addScriptMessageHandler(
        self,
        name: "callbackHandler"
    )
    let config = WKWebViewConfiguration()
    config.userContentController = contentController
    self.webView = WKWebView(frame: self.view.frame, configuration: config)
    self.webView.navigationDelegate = self
    self.view = self.webView
    let lpress = UILongPressGestureRecognizer(target: self, action: "webViewLongPressed:")
    lpress.delegate = self
    self.webView.scrollView.addGestureRecognizer(lpress)
}

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

func webViewLongPressed(sender:UILongPressGestureRecognizer!) {
    longpress = true
    if (sender.state == UIGestureRecognizerState.Ended) {
        print("Long press Ended")
        //This is where everything starts to happen
    } else if (sender.state == UIGestureRecognizerState.Began) {
        print("Long press detected.")

    }

}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {
    if let myUrlStr : String = navigationAction.request.URL!.absoluteString {

        if myUrlStr.lowercaseString.rangeOfString("/book/") != nil {
            /* Do not allow links to be tapped */
            var parts = myUrlStr.componentsSeparatedByString("/")
            let id = Int(parts[4])
            if navigationAction.navigationType == .LinkActivated && longpress == true {

                decisionHandler(.Cancel)
                let ac = actionMenu(self, id: id!, user_id: 1)
                self.presentViewController(ac, animated: true) {

                }
                longpress = false
                return
            }
        }
    }
    decisionHandler(.Allow)

}
//Build action sheet
func actionMenu(sender: UIViewController, id: Int, user_id: Int) -> UIAlertController {

    let alertController = UIAlertController(title: "Title", message: "Some message.", preferredStyle: .ActionSheet)

    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in

    }
    alertController.addAction(cancelAction)
    let someAction = UIAlertAction(title: "Some action", style: .Default) { (action) in
        //do something, call a function etc, when this action is selected
    }
    alertController.addAction(someAction)

    return alertController
}