'Disable link drag on WKWebView [duplicate]

I'm using the newest version of Xcode and Swift. I'm using a programatically created WKWebView.

If I tap on a link, wait a second and then move my finger, I can drag (and then also drop) a small box with the links title and the link itself.

For clarification: I don't mean force touch, that will show a link preview and some actions like Ad link to reading list.

How can I disable the drag link behavior?



Solution 1:[1]

I found the solution here: How to disable iOS 11 and iOS 12 Drag & Drop in WKWebView?

This is my working code:

private func disableDragAndDropInteraction() {
    var webScrollView: UIView? = nil
    var contentView: UIView? = nil
    
    if #available(iOS 11.0, *) {
        guard let noDragWebView = webView else { return }
        webScrollView = noDragWebView.subviews.compactMap { $0 as? UIScrollView }.first
        contentView = webScrollView?.subviews.first(where: { $0.interactions.count > 1 })
        guard let dragInteraction = (contentView?.interactions.compactMap { $0 as? UIDragInteraction }.first) else { return }
        contentView?.removeInteraction(dragInteraction)
    }
}
override func viewDidAppear(_ animated: Bool) {
    disableDragAndDropInteraction()
}

You also have to add disableDragAndDropInteraction() after initialising WKWebView, e.g. in viewDidLoad().

Solution 2:[2]

If you have control of the HTML loaded into the WKWebView, you can use the CSS property webkit-touch-callout like:

img, a {
    -webkit-touch-callout: none;
}

You also need to set the element's draggable attribute to false, like:

<img ... draggable="false">

I guess you could also inject these modifications using -[WKWebView evaluateJavaScript(...)] and family.

This'll avoid the need to rely on fragile subview diving and manipulation.

Tested as of iOS 15.3.

Here's some official (old) documentation: https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariCSSRef/Articles/StandardCSSProperties.html#//apple_ref/doc/uid/TP30001266-_webkit_touch_callout

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2