What is the best way to copy text to the clipboard (multi-browser)?
I have tried:
function copyToClipboard(text) {
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData("Text", text);
} else {
unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
clipboardHelper.copyString(text);
}
}
But in Internet Explorer it gives a syntax error. In Firefox, it says unsafeWindow is not defined.
A nice trick without using Flash: How does Trello access the user's clipboard?
Best Answer-推荐答案 strong>
Overview
There are three primary browser APIs for copying to the clipboard:
Async Clipboard API [navigator.clipboard.writeText]
- Text-focused portion available in Chrome 66 (March 2018)
- Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
- Text can be copied to the clipboard directly from a variable.
- Only supported on pages served over HTTPS.
- In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
document.execCommand('copy') (deprecated)
|