Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable user text selection in WebView [React-Native]

I'm trying to figure out how to disable text selection while in a React-Native WebView for my ios app. Using the css style user-select set to none on the site doesn't seem to be working while using a device or simulator but it does work in a browser. Is there a way to disable this using the React-Native WebView or do I need to use some native code to achieve this?

Using React-Native 0.30, iOS 9-10

like image 308
Ryan Wilson Avatar asked Oct 23 '25 19:10

Ryan Wilson


2 Answers

I was able to disable zooming, text selection and other pointer events on the React Native side, by wrapping WebView in a View and setting a few props:

<View pointerEvents="none">
  <WebView
    source={{ uri: webviewUrl }}
    scrollEnabled={false}
  />
</View>
like image 103
jmwicks Avatar answered Oct 26 '25 09:10

jmwicks


Assuming that you are accessing a particular url on the webview in react native, then in the url, you can use the following tricks:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
 <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<div style="font-size:80%;padding-left:10px;padding-right:10px;">


<!DOCTYPE html>
<html>
<head>
  <script>
    function absorbEvent_(event) {
      var e = event || window.event;
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      e.cancelBubble = true;
      e.returnValue = false;
      return false;
    }

    function preventLongPressMenu(node) {
      node.ontouchstart = absorbEvent_;
      node.ontouchmove = absorbEvent_;
      node.ontouchend = absorbEvent_;
      node.ontouchcancel = absorbEvent_;
    }

    function init() {
      preventLongPressMenu(document.getElementByTagName('body img'));
    }
  </script>
  <style>
    *:not(input):not(textarea) {
    -webkit-user-select: none; /* disable selection/Copy of UIWebView */
        -webkit-touch-callout: none; /* disable the IOS popup when long-press on a link */

    }
  </style>
</head>

<body onload="init()"  >


TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>TEST<br>

</body>

The above will disable text selection, but it allows other functions such as "click". (it works in both iOS and android devices)

Enjoy...

like image 33
Ken Lee Avatar answered Oct 26 '25 08:10

Ken Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!