Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1) Clipboard API: navigator.clipboard.writeText(text)
- Text can be copied to the clipboard directly from a variable.
- Only supported on pages served over HTTPS
- 2) document.execCommand('copy') 👎
- Deprecated, but still supported by many browsers
- 3) Overwrite what is being copied to the clipboard.
- element.oncopy=(e)=>{
- e.clipboardData.setData('text/plain', text);
- e.preventDefault();
- };
- //Clipboard API with fallback to document.execCommand("copy");
- function copyText(text) {
- let a;
- let textarea= text instanceof HTMLTextAreaElement;
- let input= text instanceof HTMLInputElement && text.type == "text";
- if(textarea||input){ a= text; }
- else{
- a= document.createElement("textarea");
- a.style.cssText= "opacity:0; pointer-events: none;"
- document.body.append(a);
- a.value= text;
- }
- try{
- navigator.clipboard.writeText(a.value);
- }
- catch(x){
- a.focus(); a.select();
- document.execCommand("copy");
- }
- if(textarea||input){//Do nothing}
- else a.remove();
- }
- /* Text argument can be a string or a textarea/input element;
- let a= document.querySelector("textarea");
- let b= "hello";
- copyText(a); or copy(b)
- */
- //--------------------------------------------
- let b= document.querySelector('pre'),
- c= 'i am stupid';
- b.addEventListener('copy',
- function(e){
- e.clipboardData.setData('text', c);
- e.preventDefault();
- });
- b.onclick= function() {
- try{ navigator.clipboard.writeText(c);
- alert('Copied!');
- }
- catch(err){
- try{let inp =document.createElement('input');
- document.body.appendChild(inp)
- inp.value= c; inp.select();
- document.execCommand('copy',false);
- inp.remove();
- alert('Copied!!');}
- catch(err){
- try{let e= window.getSelection(),
- f= document.createRange();
- f.selectNodeContents(b);
- e.removeAllRanges();
- e.addRange(f);
- document.execCommand("copy");
- alert('Copied!!!');}
- catch(err){alert("Couldn't copy because: "+ err.message)}
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement