Reputation: 7762
I have WKWebView
and I want to disable/remove right click menu:
I found similar issues:
webview load custom context menu
Cocoa webView - Disable all interaction
But I cant find
optional func webView(_ sender: WebView!, contextMenuItemsForElement element: [AnyHashable : Any]!,
defaultMenuItems: [Any]!) -> [Any]!
method in WKUIDelegate
or WKNavigationDelegate
Upvotes: 2
Views: 6320
Reputation: 816
None of the JavaScript solutions above worked for me as well. @spasbil's answer works great on iOS, but for those of you looking for a solution on macOS, use willOpenMenu(_:with:)
instead when subclassing WKWebView
:
import WebKit
class WebView: WKWebView {
override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
if let reloadMenuItem = menu.item(withTitle: "Reload") {
menu.removeItem(reloadMenuItem)
}
}
}
Upvotes: 3
Reputation: 279
For me nothing from the above worked. I know this is old, but if someone finds this years later like me, here is the solution:
Subclass WKWebView
, override buildMenu(with:)
and remove each item that is showing on right click, for me it was .speech
and .standardEdit
, so my final code looks like this:
import WebKit
class CustomWebView: WKWebView {
override func buildMenu(with builder: UIMenuBuilder) {
super.buildMenu(with: builder)
builder.remove(menu: .speech)
builder.remove(menu: .standardEdit)
}
}
Check this documentation page for what to remove.
Upvotes: 3
Reputation: 614
I figure it out as a most elegant way:
- (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
Upvotes: 6
Reputation: 21
You can do this, but not from Swift/Objc side.
Intercept the 'oncontextmenu' event on your html code, for example:
<body oncontextmenu='contextMenu(event)'>
Then from javascript :
function contextMenu(evt)
{
evt.preventDefault();
}
I deduced this from the following post that explain how to customize this menu:
How can the context menu in WKWebView on the Mac be modified or overridden?
Regards
Upvotes: 2