I had the same issue with Chromium on Android. In some specific cases, calling range.surroundContents(newNode) causes a very strange page reload behavior and so on. After checking the function documentation :
This method is almost equivalent to newNode.appendChild (range.extractContents ()); range.insertNode (newNode). After surrounding the boundary points, the range includes newNode.
Thus, it was obvious to apply a different way of highlighting the text. I found mark.js library that did exactly what I wanted without this annoying side effect. (Here's a JSFiddle sample that shows how it used to highlight only the selection). The difference is that the library did not use range.surroundContents(newNode) and newNode.appendChild , but rather node.replaceChild .
Based on this, here is the solution to the problem that I had, and I think this applies to your case.
function surroundRangeWithSpan(range) { var span = document.createElement('span');
And you pass window.getSelection().getRangeAt(0) to the function.
Sohayb hassoun
source share