Customize the contextual menu of WKWebView on macOS

Under iOS the WKWebView class provides a delegate method which allows to customize the contextual menu of the web engine (the menu which opens when long-pressing a link). Unfortunately under macOS the WKWebView does not provide such a method for its contextual menu. This article explains how you can customize the contextual menu of WKWebView under macOS as well. It’s not that obvious how to do so, but it can be done.

Because the WKWebView API for macOS itself does not provide anything at all which deals with the contextual menu, we need to look elsewhere. WKWebView is a subclass of an NSView on the Mac and the NSView class has methods to deal with a contextual menu. These are    


  open func willOpenMenu(_ menu: NSMenu, with event: NSEvent)

which is called before the contextual menu of the view will open and


  open func didCloseMenu(_ menu: NSMenu, with event: NSEvent)

which is called after the contextual menu has closed.

So in order to customize the contextual menu of WKWebView, we could simply subclass WKWebView and override these methods in order to modify this menu. In the „willOpenMenu“ method we can add, modify or remove menu items and in „didCloseMenu“ we would reset anything that needs to be reverted back to normal.

In „willOpenMenu“ the parameter „menu“ represents the contextual menu, so we can easily inspect all the available menu items, remove what we don’t need and add all the new menu items we want to have in the menu. This sounds easy, but there are a few issues.

Because Apple does not officially provide a way to customize the contextual menu, nothing is officially documented. So some simple reverse engineering is required to find out the meaning of the default menu items and their actions.

  • The first thing we can find out is that the „identifier“ property of the menu items is very clear about the meaning, and these identifiers look very stable – they haven’t changed between different macOS releases.
  • The second thing we can find out is that if a link is clicked, we find menu items with the ID „WKMenuItemIdentifierOpenLinkInNewWindow“ and „WKMenuItemIdentifierDownloadLinkedFile“. If an Image was clicked we find „WKMenuItemIdentifierOpenImageInNewWindow“ and „WKMenuItemIdentifierDownloadImage“ and for videos „WKMenuItemIdentifierOpenMediaInNewWindow“ and „WKMenuItemIdentifierDownloadMedia
  • Another thing we can find out is that the menu and its items do not contain any information about the context, e.g. the link, image or other element on which the contextual menu was opened is totally unknown.

The first point makes it easy to remove all the menu items which deal with features we do not want to provide in out App. We just need to check the identifiers and remove items whose identifier match these features.

But the latter point is a problem, because if we want to add custom menu items which deal with the current context (the clicked link, image, etc), we need to know about this context.

So how we can solve this issue? The solution I’ve found is the following:

Because the context is unknown but the context can only be a link, an image, a frame or a video (something that can be clicked and which has a URL) and for all these contexts there’s already a default menu item which opens the context object in a new window, why not simply use these existing menu items and then intercept the default action for the menu item and replace it with our custom action. All the default actions to open an object in a new window will call the following method of the standard navigation delegate of WKWebView:


  func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?

And this delegate method is getting the required context via the navigationAction parameter, which means the URL of the object. The delegte method itself and its parameters are unable to provide any information about our custom action of the menu item, so we have to find another way to get this information there.

We already have overridden the WKWebView class in order to intercept the contexual menu, therefore we could simply add another property to this subclass where we save the custom action for the selected contextual menu item. In the navigation delegate method above it’s then easy to check this property and use it to decide wether to continue with the default action (creating a new window) or continue with the custom action.

We now have everything we need to implement our own custom menu items for the contextual menu.

At first we implement an enum for all our custom actions:


  enum ContextualMenuAction {
    case openInNewTab
    case addToBookmarks
    // add any other actions you want to have
  }

Now we implement the subclass for the WKWebView, including the property contextualMenuAction which will hold the custom action that was selected from within the contextual menu. This property is declared as optional, so it will be nil if a default menu item is selected.


  class MyWebView: WKWebView {

    var contextualMenuAction: ContextualMenuAction?

Now we override the willOpenMenu method, which will be called when the contextual menu opens and where we modify the menu according to our needs.


  override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
    super.willOpenMenu(menu, with: event)
    
    var items = menu.items
    
    // In our example we don't need Download options, so we remove these menu items
    for idx in (0..<items.count).reversed() {
      if let id = items[idx].identifier?.rawValue {
        if id == "WKMenuItemIdentifierDownloadLinkedFile" ||
           id == "WKMenuItemIdentifierDownloadImage" ||
           id == "WKMenuItemIdentifierDownloadMedia" {
          items.remove(at:idx)
        }
      }
    }
    
    // For all default menu items which open a new Window, we add custom menu items
    // to open the object in a new Tab and to add them to the bookmarks.
    for idx in (0..<items.count).reversed() {
      if let id = items[idx].identifier?.rawValue {
        if id == "WKMenuItemIdentifierOpenLinkInNewWindow" ||
           id == "WKMenuItemIdentifierOpenImageInNewWindow" ||
           id == "WKMenuItemIdentifierOpenMediaInNewWindow" ||
           id == "WKMenuItemIdentifierOpenFrameInNewWindow" {
        
          let object:String
          if id == "WKMenuItemIdentifierOpenLinkInNewWindow" {
            object = "Link"
          } else if id == "WKMenuItemIdentifierOpenImageInNewWindow" {
            object = "Image"
          } else if id == "WKMenuItemIdentifierOpenMediaInNewWindow" {
            object = "Video"
          } else {
            object = "Frame"
          }
          
          let action = #selector(processMenuItem(_:))

          let title = "Open \(object) in new Tab"
          let tabMenuItem = NSMenuItem(title:title, action:action, keyEquivalent:"")
          tabMenuItem.identifier = NSUserInterfaceItemIdentifier("openInNewTab")
          tabMenuItem.target = self
          tabMenuItem.representedObject = items[idx]          
          items.insert(tabMenuItem, at: idx+1)
          
          let title = "Add \(object) to Bookmarks"
          let bookmarkMenuItem = NSMenuItem(title:title, action:action, keyEquivalent:"")
          bookmarkMenuItem.identifier = NSUserInterfaceItemIdentifier("addToBookmarks")
          bookmarkMenuItem.target = self
          bookmarkMenuItem.representedObject = items[idx]
          items.insert(bookmarkMenuItem, at: idx+2)
        }
      }
    }
    
    menu.items = items
  }

The first action is to call super so that the WKWebView can do everything it needs to do for the menu. Then the menu items will be modified to our needs. In this example all the download items will be removed from the contextual menu. The second step is to look for the default menu items which open an object (link, image video, frame) in a new window and then create a new custom menu item which is supposed to open this object in a new tab and a second menu item which is supposed to save the object into the bookmark (this article doesn’t cover how to do this, it’s just an example how to add such menu items and later how to detect and process the selection of these menu items). The new custom menu items use the „representedObject“ property to store the default menu item which is needed later when the user has selected our custom menu items. Our new custom menu items are then inserted after the original menu item within the contextual menu. Now the macOS will show the contextual menu with all our customizations.

The method which is called when selecting our custom menu items is implemented next.


  @objc func processMenuItem(_ menuItem: NSMenuItem) {
    self.contextualMenuAction = nil

    if let originalMenu = menuItem.representedObject as? NSMenuItem {
    
      if menuItem.identifier?.rawValue == "openInNewTab" {
        self.contextualMenuAction = .openInNewTab
      } else if menuItem.identifier?.rawValue == "addToBookmarks" {
        self.contextualMenuAction = .addToBookmarks
      }
      
      if let action = originalMenu.action {
        originalMenu.target?.perform(action, with: originalMenu)
      }
    }
  }

At first the property contextualMenuAction is initialized to nil. Then we check if the property representedObject contains a NSMenuItem, in which case this menu item is the original default menu item and we use its target and action to trigger its default action. But before that, we need to set the property contextualMenuAction to the action that is bound to our custom menu item, so when the navigation delegate of WKWebView is called to create a new window, we can check contextualMenuAction to find out the action that is really supposed to be triggered.

And finally we override didCloseMenu to make sure that the property contextualMenuAction is reset to nil after the menu has closed. The navigation delegate to create new windows can be also called by WKWebView without having any contextual menu involved (for example if JavaScript code of the web site creates new windows), therefore this property can’t be allowed to keep its last value until the contextual menu is used again.


  override func didCloseMenu(_ menu: NSMenu, with event: NSEvent?) {
    super.didCloseMenu(menu, with: event)

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
      self.contextualMenuAction = nil
    }
  }

It is important set contextualMenuAction to nil after a delay, because the contextual menu action is processed asynchronously. Which means the menu can close before the action is actually triggered and the navigation delegate method is called. Theoretically you can also clear this property within the navigation delegate method, but in practice it can happen that this method is not called if something goes wrong while processing the menu action (like there’s no network connection, the URL is invalid etc). Therefore it’s better to clear the property after closing the menu here.

And as the final action we need to implement the navigation delegate method of WKWebView which is called to create a new window:


  func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration,
                  for navigationAction: WKNavigationAction,
                  windowFeatures: WKWindowFeatures) -> WKWebView? {

    if let customAction = (webView as? MyWebView)?.contextualMenuAction {
      let url = navigationAction.request.url

      if customAction == .openInNewTab {
        createNewTab(for:url)
      } else if customAction == .addToBookmarks {
        addBookmark(url:url)
      }
      return nil

    } else {
      return createWebView(with:configuration)
    }
  }

First we check if the  property contextualMenuAction is not nil. In this case one of the custom actions must be performed. The value of this property tells us, which action this is. Otherwise the default action (creating a new window) must be performed.

You see that it’s not too complicated to implement a custom contextual menu for WKWebView on the Mac. Basically we need to „hijack“ one of the existing default menu items to let the WKWebEngine pass the context (the URL of the object for which the contextual menu was opened) to the App which would be otherwise inaccessible. The solution is not totally „clean“ because we have to use undocumented identfiers of the default menu items, but because these are simple strings you can’t break anything. The worst thing that can happen is that these identifiers change in future macOS releases and then the custom menu items will be missing unless you add the new identifieres as well. But this is very unlikely.

Leave a Reply

Your email address will not be published. Required fields are marked *