Search code examples
swiftwebkitwkwebview

Set UIContextMenu for WKWebView links


enter image description here

How can we set a custom context menu for links within WKWebView?

You can set the context menu on an item by doing something like this:

    let interaction = UIContextMenuInteraction(delegate: self)
    someItem.addInteraction(interaction)

and adding the UIContextMenuInteractionDelegate delegate:

 func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { (_) -> UIMenu? in
            let shareAction = UIAction(title: "Send to Friend", image: UIImage(systemName: "square.and.arrow.up")) { _ in
                // Pressed
            }
            let menu = UIMenu(title: "", children: [shareAction])
            return menu
        }
        return configuration
    }

How can you use a custom context menu when a user holds on a link in a WKWebView?


Solution

  • You should implement contextMenuConfigurationForElement UI delegate method for your WKWebView e.g.:

    override func viewDidLoad() {
        ...
        webView?.uiDelegate = self
    }
    
    extension ViewController : WKUIDelegate {
        
        func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) {
            let share = UIAction(title: "Send to Friend") { _ in print("Send to Friend") }
            let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
              UIMenu(title: "Actions", children: [share])
            }
            completionHandler(configuration)
        }
    }