js handle copy on page code example
Example: 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 || '' ) )
};
}