Search code examples
javascripttypescriptgetselection

Typescript getSelection disappear


In Vue and typescript I have my own context menu:

<context-menu id="context-menu" ref="ctxMenu">
      <li @click="ctxMenuClickItem1($event)" v-on:mouseover="menuItemMouseover($event)" v-on:mouseleave="menuItemMouseleave($event)" v-bind:style="getMenuItemStyle()" >Open in TMS</li>
      <li @click="ctxMenuClickItem2($event)" v-on:mouseover="menuItemMouseover($event)" v-on:mouseleave="menuItemMouseleave($event)" v-bind:style="getMenuItemStyle()" >Open in OnDemand</li>
      <li @click="doCopy()" >Copy</li>
    </context-menu>

And when I selected text on the page and then I click third item in context menu (doCopy) the selection disappear.

Do copy function looks like this:

 doCopy: function () {
  debugger;
  var selection = window.getSelection();
},

and after click selection is empty: selection.toString() is ""

How to copy selected text?


Solution

  • When you click in the context menu, your selection is collapsing (or reset) maybe because moving focus. You need to get a selection when the event 'contextmenu' triggered, and restore selection in doCopy. Example for JS:

    var range = document.createRange();
    docucment.addEventListener('contextmenu', (ev) => {
        let selection = window.getSelection();
        if(selection.rangeCount > 0) {}
        range = selection.getRangeAt(0);
    })
    doCopy = function(){
      let selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
      document.execCommand('copy');//save selection in buffer
    
    }
    

    If you select text in contenteditable element, you need set focus in that element.