#StackBounty: #javascript #html #css #swift #wkwebview WKWebView – prevent automatic scrolling triggered by user text selection

Bounty: 50

When a user performs a tap and hold gesture to select a word and then drags their finger towards either the top or bottom edges of the screen, the page automatically scrolls in order to accommodate the selection.

here is a short clip demonstrating it

I would like to prevent this behavior inside a WKWebView.

Here is what I have tried so far:

in a bridge.js file which is accessible to the webview:

var shouldAllowScrolling = true;

document.addEventListener('selectionchange', e => {
    shouldAllowScrolling = getSelectedText().length === 0;
            shouldAllowScrolling: shouldAllowScrolling
    console.log('allow scrolling = ', shouldAllowScrolling);

and then in a WKScriptMessageHandler implementation:

public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
        switch message.name
        case "selectionChangeHandler":
            let params = paramsDictionary(fromMessageBody: message.body)
            let shouldEnableScrolling = params["shouldAllowScrolling"] as? Bool ?? true
            cell?.webView.scrollView.isScrollEnabled = shouldEnableScrolling
            cell?.webView.scrollView.isUserInteractionEnabled = shouldEnableScrolling // not together with the line above 
            fatalError("(#function): received undefined message handler name: (message.name)")

Similarly, I have tried calling the preventDefault() function directly in the javascript file for a bunch of events, namely scroll and touchmove, like so:

document.addEventListener('touchmove', e => {
    if (!shouldAllowScrolling) {
}, {passive: false});

both methods successfully prevent scrolling when some text is selected but do not override the behavior described at the very top of my question.

I can accept solutions in either Swift and JavaScript or a mix of both.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.