Strange firefox / javascript behavior using ranges

Hey, so I'm working with ranges, I'm trying to limit the choices a user can make on a page. I mean, the user can select whatever he wants, but the choice cannot exceed the boundaries that I set.

First, I define "borders" with a specific range. Then I compare the current user selection with the given range if the current start of the selection is below the borders OR the current end of the selection is above the borders that I adjust accordingly, so the user's selection never exceeds the range / selection of the borders of the borders.

The function below only works if I get a warning before starting the process. If I remove the warning, then firefox behaves strangely (like choosing a different part of the page, etc.).

Question: why the following code works with a warning and why it does not work as expected without a warning?

Thank!

var range = document.createRange(); // this is the boundaries range
range.selectNodeContents(document.getElementById("container"));

function test(){
            alert("let go"); // if I remove this alert, the code doesn't work as expected, WHY?!
            if(window.getSelection().rangeCount == 0){
                return;
            }
            var curRange = window.getSelection().getRangeAt(0);
            if(curRange.compareBoundaryPoints(Range.START_TO_START, range) < 0){
                curRange.setStart(range.startContainer,range.startOffset);
            }

           if(curRange.compareBoundaryPoints(Range.END_TO_END, range) > 0){
               curRange.setEnd(range.endContainer,range.endOffset);
            }
        }
+3
source share
1 answer

First, to work in other browsers (except IE <= 8, which has a completely different way to do this), you will need to re-select the range. Secondly, to make it work in Firefox, you need to work with a clone of the original selected range:

function test(){
    var sel = window.getSelection();
    if (sel.rangeCount == 0) {
        return;
    }
    var curRange = sel.getRangeAt(0).cloneRange();
    if (curRange.compareBoundaryPoints(Range.START_TO_START, range) < 0) {
        curRange.setStart(range.startContainer,range.startOffset);
    }
    if (curRange.compareBoundaryPoints(Range.END_TO_END, range) > 0) {
        curRange.setEnd(range.endContainer,range.endOffset);
    }
    sel.removeAllRanges();
    sel.addRange(curRange);
}
+5
source

Source: https://habr.com/ru/post/1777098/