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;
window.webkit.messageHandlers.selectionChangeHandler.postMessage(
{
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
default:
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) {
e.preventDefault()
}
}, {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.