简体   繁体   中英

javascript automatic copy text to clipboard

I'm trying to copy content to clipboard without user action but this doesn't work. is because firefox detect the origin of the action ? (click() function and not user real clic)

https://jsfiddle.net/ukj871dc/

<div id='div'>some text</div>

$("<button id='clickme'>clickme</button>").insertAfter( "#div" );
$("<textarea id='temptext'></textarea>").insertAfter( "#clickme" );
$("#temptext").css({"position": "fixed", "bottom": "0px", "left": "0px", "opacity": "0"});

// next one doesn't work
setTimeout(function () {document.getElementById("clickme").click();}, 2000);

$("#clickme").click(function(){
var textToCopy = $('#div').text();
$('#temptext').val(textToCopy);
$('#temptext').select();
document.execCommand('copy');                                     
});

It's just for personal interest don't bother long explanation you could give me links to documentation as well

If you're using Firefox pre-41, you need to enable clipboard support manually in the user.js preference file. Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Browser_compatibility

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM