ioswkwebview

How to add a custom menu item for selected text in WKWebView?


I want to add a custom menu item to the selected text context menu of WKWebView in iOS/iPadOS.

Until now I only see code examples and delegate methods to build a custom context menu for selected links, but that is not what I need. I want to extend the context menu item for for selected text. See screenshot.

How do I do that?

enter image description here


Solution

  • It turns out that the generic buildMenu method also works with WKWebView. Adding a custom context menu item is as simple as this:

    override func buildMenu(with builder: any UIMenuBuilder) {
         
        let customMenuItem = UIAction(title: "Custom Title", image: UIImage(systemName: "star")) { action in
            // Handle menu item action here
        }
        
        let menu = UIMenu(title: String(), image: nil, identifier: nil, options: .displayInline, children: [customMenuItem])
        builder.insertSibling(menu, afterMenu: .standardEdit) // Or any other standard menu
        
        super.buildMenu(with: builder)
    }
    

    Works with iOS 16 or newer