Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override wkwebview hyperlink action sheet

Tags:

ios

swift

When you long press on a hyperlink in a WkWebview you get an action sheet. I want to override that action sheet with my own set of options when it is long pressed, but behave normally otherwise. I can get the the long press event, but I don't know how to:

  1. Prevent the default actions sheet for showing
  2. Prevent the webview from navigating to the URL on long press end.
  3. Get the underlying href URL that the webview was being direct to or the html a tag itself and associated attributes such as an ID.
like image 468
Jed Grant Avatar asked Dec 14 '15 19:12

Jed Grant


1 Answers

One simple (but radical) way to cancel an action sheet is to override presentViewController:animated:completion: in your app's root view controller.

Swift 3 sample

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)
}

You can retrieve the link's URL from alertController.title, and if you need to retrieve other attributes, I suggest you look at this commit to Firefox iOS, that uses a JS script handler to find the clicked element and send its attributes back to the app.

Also you'd need to write some logic to prevent cancelling any other alert sheet other than WKWebView's, that you app may use.

like image 196
Greg de J Avatar answered Sep 19 '22 15:09

Greg de J