Home > Enterprise >  WkWebView selects text when interacting with "user-select: none" area
WkWebView selects text when interacting with "user-select: none" area

Time:09-23

In an iOS iPad app with a single fullscreen WKWebView, when long-pressing into an area with user-select:none on it, random the first text in the next best area without user-select: none is selected.

How can one prevent this behavior? I would expect that long-pressing in any area but text would just be ignored. Note that even the body has user-select:none, didn't help either.

Example content:

<style>
  .with-select {
    -webkit-user-select: text;
    -moz-user-select: text;
    user-select: text;
  }
  .no-select {
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none;
  }
</style>
<body class="no-select">
  <div id="nav" class="no-select">
    Here be the navigation, user's will long-press items here to open a context menu
  </div>
  <div id="text" class="with-select">
    Seemingly random text is selected in here, even when things in "nav" are long-pressed
  </div>
</body>

CodePudding user response:

It seems that on IOS the first word in the first text the browser finds that doesn't have user-select: none is selected.

This snippet puts a dummy 'word' after the nav div which it positions with CSS off screen. This stops the nav text being selectable.

However, this dummy word did become selectable by selecting the first word in #text and dragging back to the end of nav. The way round this seems to be to put dummy offscreen above everything (not to the left). Just to be sure if the 'word' does get picked up somehow it is made to be just a non breaking space (an ordinary space is not enough).

Experiments with trying to replace the dummy div with a pseudo element did not work, it was not picked up by itself but only alongside the first word of text.

So, this is not nice as it involves putting a seemingly spurious element between nav and text but I put it here in case it helps in a particular use case.

.with-select {
  -webkit-user-select: text;
  -moz-user-select: text;
  user-select: text;
}

.no-select {
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

.dummy {
  margin-top: -3000px;
  position: absolute;
}
<div id="nav" class="no-select">
  Here be the navigation, user's will long-press items here to open a context menu
</div>
<div class="dummy with-select">&nbsp;</div>
<div id="text" class="with-select">
  Seemingly random text is selected in here, even when things in "nav" are long-pressed
</div>

  • Related