如何使用JavaScript复制到剪贴板?

将文本复制到剪贴板的最佳方法是什么?(多浏览器)

我试过了:

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

但是在Internet Explorer中,它会给出语法错误。在Firefox中,显示为unsafeWindow is not defined

一个没有Flash的好窍门:Trello如何访问用户的剪贴板?

Sam猪猪2020/03/09 12:57:15

I have used clipboard.js.

We can get it on npm:

npm install clipboard --save

And also on Bower

bower install clipboard --save

Usage & examples are at https://zenorocha.github.io/clipboard.js/.

Davaid阳光2020/03/09 12:57:15

Copy text from HTML input to the clipboard:

 function myFunction() {
   /* Get the text field */
   var copyText = document.getElementById("myInput");

   /* Select the text field */
   copyText.select();

   /* Copy the text inside the text field */
   document.execCommand("Copy");

   /* Alert the copied text */
   alert("Copied the text: " + copyText.value);
 }
 <!-- The text field -->
 <input type="text" value="Hello Friend" id="myInput">

 <!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>

Note: The document.execCommand() method is not supported in Internet Explorer 9 and earlier.

Source: W3Schools - Copy Text to Clipboard

凯神乐2020/03/09 12:57:15

In browsers other than IE you need to use a small flash object to manipulate the clipboard, e.g.

神离伊芙妮2020/03/09 12:57:15

如果您想要一个非常简单的解决方案(集成时间少于5分钟)并且看起来开箱即用,那么Clippy是一些更复杂的解决方案的不错选择。

它是由GitHub的联合创始人编写的。以下示例Flash嵌入代码:

<object
   classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   width="110"
   height="14"
   id="clippy">
  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>
  <embed
     src="/flash/clippy.swf"
     width="110"
     height="14"
     name="clippy"
     quality="high"
     allowScriptAccess="always"
     type="application/x-shockwave-flash"
     pluginspage="http://www.macromedia.com/go/getflashplayer"
     FlashVars="text=#{text}"
     bgcolor="#{bgcolor}"/>
</object>

切记#{text}用需要复制的文字和#{bgcolor}颜色替换

TomMandy2020/03/09 12:57:15

以下方法适用于Chrome,Firefox,Internet Explorer和Edge,以及最新版本的Safari(复制支持已添加到2016年10月发布的版本10中)。

  • 创建一个textarea并将其内容设置为要复制到剪贴板的文本。
  • 将文本区域附加到DOM。
  • 在文本区域中选择文本。
  • Call document.execCommand("copy")
  • Remove the textarea from the dom.

Note: you will not see the textarea, as it is added and removed within the same synchronous invocation of Javascript code.

Some things to watch out for if you are implementing this yourself:

  • For security reasons, this can only called from an event handler such as click (Just as with opening windows).
  • Internet Explorer will show a permission dialog the first time the clipboard is updated.
  • Internet Explorer, and Edge will scroll when the textarea is focused.
  • execCommand() may throw in some cases.
  • Newlines and tabs can get swallowed unless you use a textarea. (Most articles seem to recommend using a div)
  • The textarea will be visible while the Internet Explorer dialog is shown, you either need to hide it, or use the Internet Explorer specific clipboardData API.
  • In Internet Explorer system administrators can disable the clipboard API.

The function below should handle all of the following issues as cleanly as possible. Please leave a comment if you find any problems or have any suggestions for improving it.

// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
// Internet Explorer: The clipboard feature may be disabled by
// an administrator. By default a prompt is shown the first
// time the clipboard is used (per session).
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
}

https://jsfiddle.net/fx6a6n6x/