title: WKWebView - prevent automatic scrolling triggered by user text selection
body: <p>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.</p>
  
  <p><a href="https://youtu.be/Fw4cqH4gt6Y" rel="noreferrer">here is a short clip demonstrating it</a></p>
  
  <p>I would like to prevent this behavior inside a <code>WKWebView</code>.</p>
  
  <p>Here is what I have tried so far:</p>
  
  <p>in a <code>bridge.js</code> file which is accessible to the webview:</p>
  
  <pre><code>var shouldAllowScrolling = true;
  
  document.addEventListener('selectionchange', e =&gt; {
      shouldAllowScrolling = getSelectedText().length === 0;
      window.webkit.messageHandlers.selectionChangeHandler.postMessage(
          {
              shouldAllowScrolling: shouldAllowScrolling
          });
      console.log('allow scrolling = ', shouldAllowScrolling);
  });
  </code></pre>
  
  <p>and then in a <code>WKScriptMessageHandler</code> implementation:</p>
  
  <pre><code>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)")
          }
      }
  </code></pre>
  
  <p>Similarly, I have tried calling the <code>preventDefault()</code> function directly in the javascript file for a bunch of events, namely <code>scroll</code> and <code>touchmove</code>, like so:</p>
  
  <pre><code>document.addEventListener('touchmove', e =&gt; {
      if (!shouldAllowScrolling) {
          e.preventDefault()
      }
  }, {passive: false});
  </code></pre>
  
  <p>both methods successfully prevent scrolling when some text is selected but do not override the behavior described at the very top of my question.</p>
  
  <p>I can accept solutions in either Swift and JavaScript or a mix of both.</p>