WKWebView 禁用右键菜单

WKWebView disable right click menu

我有 WKWebView,我想 disable/remove 右键单击​​菜单:

我发现了类似的问题:

webview load custom context menu

Cocoa webView - Disable all interaction

但是我找不到

optional func webView(_ sender: WebView!,  contextMenuItemsForElement element: [AnyHashable : Any]!, 
     defaultMenuItems: [Any]!) -> [Any]!

methodWKUIDelegateWKNavigationDelegate

您可以这样做,但不能从 Swift/Objc 方面进行。

在您的 html 代码中拦截 'oncontextmenu' 事件,例如:

<body oncontextmenu='contextMenu(event)'>

然后从 javascript :

function contextMenu(evt)
{
    evt.preventDefault();
}

我从以下解释如何自定义此菜单的 post 中推断出这一点:

此致

myWKView.allowsBackForwardNavigationGestures = false

我认为这是一种最优雅的方式:

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [webView evaluateJavaScript:@"document.body.setAttribute('oncontextmenu', 'event.preventDefault();');" completionHandler:nil];
}

Keep in mind that some JavaScripts can override this behaviour

对我来说,以上方法均无效。我知道这已经过时了,但如果有人像我一样在几年后发现了这个,这里是解决方案:

子类 WKWebView,覆盖 buildMenu(with:) 并删除右键单击时显示的每个项目,对我来说是 .speech.standardEdit,所以我的最终代码看起来像这样:

import WebKit

class CustomWebView: WKWebView {

    override func buildMenu(with builder: UIMenuBuilder) {
        super.buildMenu(with: builder)
        
        builder.remove(menu: .speech)
        builder.remove(menu: .standardEdit)
    }
    
}

检查 this documentation page 要删除的内容。