简体   繁体   中英

How I can access the selected text in IE11 from context menu, and copy to Clipboard

I have tried anything to get the selected text for a context menu, but it is not working in IE11. For context menu adding I have added some code in registry, and a htm file with a Javascript. First I have tried this:

var parentwin = external.menuArguments;
var doc = parentwin.document;
var sel = doc.selection;
var rng  = sel.createRange();
var selectedtext = new String(rng.text);

then I have read in IE11 documentation, the document.selection has been repalced in the API with window.getSelection();

So I have tried any variant, window.getSelection... nothing works...

Any idea how I can access the selected text?

And I have searching also how I can copy to the clipboard.. in chrome I have used this script:

function copyToClipboard(text){
 var copyDiv = document.createElement('div');
 copyDiv.contentEditable = true;
 document.body.appendChild(copyDiv);
 copyDiv.innerHTML = text;
 copyDiv.unselectable = "off";
 copyDiv.focus();
 document.execCommand('SelectAll');
 document.execCommand("Copy", false, null);
 document.body.removeChild(copyDiv);
        }  

Finally I have found the solution: (tested in IE11)

var parentwin = external.menuArguments
var selectedText = getSel();                

function getSel(){
  var w=window,d=parentwin.document,gS='getSelection';
  return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}

parentwin.console.log("the selected text is:"+sel);
copyToClipboard(selectedText);


function copyToClipboard(s) {           //only works in IE :(
if (window.clipboardData && clipboardData.setData) {
    clipboardData.setData('text', s);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM