How do I copy from JavaScript to the clipboard?

Asked 2 years ago, Updated 2 years ago, 18 views

What is the best way to make a clipboard copy in a multi-browser environment?

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);
    }
}

I tried it like this, and a Syntex error occurs on the Internet Explorer. And at Firefox, It says unsafeWindow is not defined. What went wrong? What should I do?

javascript

2022-09-22 22:10

1 Answers

Automatically copying to the clipboard can sometimes lead to very dangerous consequences. So in most browsers, it's made hard to do that. Except for IE. So, I'm

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

Use an expedient to prompt the user to press Ctrl+C and enter directly.

<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>

<script>
  function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
</script>
You can apply to

like this. That way, the Clipboard, such as radiation is very safe. Passive radiation of directly because users.


2022-09-22 22:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.