Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

navigator.clipboard is undefined

ou can write an all-in-one wrapper function.

if in secure context (https) : use navigator clipboard api
if not : use the 'out of viewport hidden text area' trick
// return a promise
function copyToClipboard(textToCopy) {
    // navigator clipboard api needs a secure context (https)
    if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard api method'
        return navigator.clipboard.writeText(textToCopy);
    } else {
        // text area method
        let textArea = document.createElement("textarea");
        textArea.value = textToCopy;
        // make the textarea out of viewport
        textArea.style.position = "fixed";
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((res, rej) => {
            // here the magic happens
            document.execCommand('copy') ? res() : rej();
            textArea.remove();
        });
    }
}
use :

copyToClipboard("I'm going to the clipboard !")
    .then(() => console.log('text copied !'))
    .catch(() => console.log('error'));
Comment

navigator.clipboard is undefined

On Firefox, HTTPS is required
Comment

PREVIOUS NEXT
Code Example
Javascript :: run from build react 
Javascript :: add char in specific index stirng javascript 
Javascript :: uuid timestamp for javascript 
Javascript :: javascript append element to array 
Javascript :: react native text input right 
Javascript :: csrf token in js laravel 
Javascript :: jquery on ready 
Javascript :: clear input field jquery 
Javascript :: joi validation custom message in node 
Javascript :: detect emoji in string javascript 
Javascript :: react native header height 
Javascript :: ionic 3 alert 
Javascript :: chamar arquivo javascript no html 
Javascript :: compare two arrays and return the difference javascript 
Javascript :: js regex with variable 
Javascript :: react save to local storage 
Javascript :: timestamp to date javascript 
Javascript :: print value in jquery 
Javascript :: javascript backslash 
Javascript :: two digit js' 
Javascript :: prevent a page from refreshing in react 
Javascript :: count array in javascript 
Javascript :: send mail with javascript 
Javascript :: js get random element in array 
Javascript :: jquery selector this and class 
Javascript :: chrome input disable autofill 
Javascript :: nuxt looks for npm_modules on express 
Javascript :: delta time js 
Javascript :: jquery move element to another without losing events 
Javascript :: javascript print random word from list 
ADD CONTENT
Topic
Content
Source link
Name
1+2 =