-1

I need to copy any selection from a webpage to the clipboard, it can be on a div, text input, password input, span, etc.

I have the following function that does this for me, but the challenge is have the returned value from the function to be set on the clipboard

const getSelectionText = () => {
  let text = "";
  let activeDomElement = document.activeElement;
  let activeDomElementTagName = activeDomElement ? activeDomElement.tagName.toLowerCase() : null;

 if (
   (activeDomElementTagName === 'textarea') || (activeDomElementTagName ===  'input' &&
  /^(?:text|search|password|tel|url)$/i.test(activeDomElement.type)) &&
(typeof activeDomElement.selectionStart === "number")
 ) {   
     text = activeDomElement.value.slice(activeDomElement.selectionStart,   activeDomElement.selectionEnd);
   } else if (window.getSelection) {
     text = window.getSelection().toString();
  } 

return text;
}

Any idea, or links to resources would be helpful, thanks

Thabo
  • 1,303
  • 2
  • 19
  • 40

2 Answers2

1

Have a look at the example from w3schools.It is a basic example.

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

You can also use this - Just call myFunction with your returned text as an argument.

function myFunction(arg) {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value",arg);
    x.select();
    document.execCommand("Copy");
    alert("Copied the text: " + x.value);
    document.removeChild(x);
}
vishugosain
  • 180
  • 1
  • 9
0

document.execCommand("copy") this will copied all your selected text !

       function copySelectionText(){
        var copysuccess // var to check whether execCommand successfully executed
        try{
            copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard
        } catch(e){
            copysuccess = false
        }
        return copysuccess
    }
    document.body.addEventListener('mouseup', function(e){
        var copysuccess = copySelectionText() // copy user selected text to clipboard
        if(copysuccess) {
           document.getElementById('paste').style.display = "block";
        }
    }, false)
     <h3>Late</h3>
    <p>dsfjdslkfjdslkfjdsklfj</p>
    <code>Cdoing is godo for a wite </code>


    <textarea placeholder="Paste Here with [Ctrl + V ]" style="display:none;" id="paste"> </textarea>
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52