window.getSelection() does not work properly in chrome

51 views Asked by At

Im trying to create a simple rich text editor with vanilla js in order to learn more about selection object (window.getSelection()), and as mdn mentioned in the js documentation to ensure u have a range of text selected by the user the rangeCount property must be greater than zero, the type property is a "Range" and the isCollapsed property equals to false, otherwise there is no text selected. Thats works correctly in most browsers but its not the case in chrome. The selection object returned a range even there is nothing selected.

         <div id="wysiwyg" contenteditable="true">
            <p>
             text
            </p>
            <ul>
              <li>a</li>
              <li>b</li>
              <li>c</li>
            </ul>
          </div>

          <div>
            <button type="button" id="click">
              click
            </button>
          </div>
(() => {
  const button = document.getElementById("click");
  
  button.addEventListener("click", (event) => {
    
    event.preventDefault();
    event.stopPropagation()

    let selection = window.getSelection(),
        rangeCount = (selection.rangeCount > 0)  ? selection.rangeCount : null,
        range = null;

    if(rangeCount && selection.type === "Range" && selection.isCollapsed === false ) {
     
      // only MoZilla Firefox allows more than one selection (range could be greater than 1)
      if (rangeCount > 1) {  

        for (let index = 0; index < rangeCount; index++) {
          
          range[index] = selection.getRangeAt(index);
        }

      }else {

        range = selection.getRangeAt(0);
      }
    } 

    console.log(range);
 
  });
})();

The returned selection object must have different values when there is no text selected.

0

There are 0 answers