javascript prompt copy to clipboard code example
Example 1: js copy string to clipboard
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
Example 2: js copy to clipboard cross browser
function copy2clipboard( text, callback ) {
if ( navigator.clipboard ) {
navigator.clipboard.writeText( text )
.then( function(){
callback && callback();
}).catch( function( err ){
errorMessage( err );
});
}
else {
var textArea = document.createElement( 'textarea' );
textArea.setAttribute( 'style', 'width:1px;border:0;opacity:0;' );
document.body.appendChild( textArea );
textArea.value = text;
textArea.select();
try {
var isCopied = document.execCommand('copy');
isCopied ? ( callback && callback() ) : errorMessage();
}
catch( err ) {
errorMessage( err );
}
document.body.removeChild( textArea );
}
function errorMessage( err ) {
alert( 'Copy to clipboard failed ' + ( err || '' ) )
};
}