constcopyText=(text)=>{// clipboardData Copy what you need on the page to the clipboardconst clipboardData =window.clipboardData;if(clipboardData){
clipboardData.clearData();
clipboardData.setData('Text', text);returntrue;}elseif(document.execCommand){// Note that document.execCommand is deprecated but some browsers still support it. Remember to check the compatibility when using it// Get the content to be copied by creating a dom elementconst el =document.createElement('textarea');
el.value= text;
el.setAttribute('readonly','');
el.style.position='absolute';
el.style.left='-9999px';document.body.appendChild(el);
el.select();// Copy the current content to the clipboarddocument.execCommand('copy');// delete el nodedocument.body.removeChild(el);returntrue;}returnfalse;};copyText('hello!');// ctrl + v = copyText | true
Also works on safari!functioncopyToClipboard(){var copyText =document.getElementById("share-link");
copyText.select();
copyText.setSelectionRange(0,99999);document.execCommand("copy");}
// Copy to clipboard in node.jsconst child_process =require('child_process')// This uses an external application for clipboard access, so fill it in here// Some options: pbcopy (macOS), xclip (Linux or anywhere with Xlib)constCOPY_APP='xclip'functioncopy(data, encoding='utf8'){const proc = child_process.spawn(COPY_APP)
proc.stdin.write(data,{encoding})
proc.stdin.end()}
const el =document.createElement('textarea');
el.value= str;//str is your string to copydocument.body.appendChild(el);
el.select();document.execCommand('copy');// Copy commanddocument.body.removeChild(el);
// promise is returned for outcome;// might require browser permissions;// prefer this API as "execCommand" is deprecatednavigator.clipboard.writeText("some text").then(function(){/* clipboard successfully set */},function(){/* clipboard write failed */});
//Copy the text in a html textarea or input field using javascript//First you have to select the text and then copy it. You can do both with a single function//So first, make a button that will call this function 'copy' onclick://Give your text area or input the id, eg, id='textArea'functioncopy(){document.getElementById("textArea").select();document.execCommand("copy");alert("Text copied to clipboard");//optional}//The select() method will select the text in the input area or text area.//The execCommand("copy") will do the copying to your clipboard and you can then paste//This will copy your text to both PC and phone clipboard using simple javascript