将选定文本复制到剪贴板而不使用flash——必须是跨浏览器。

时间:2022-04-25 09:43:23

I want to have a button which selects the text in a textarea and copies it to the clipboard. I can't seem to find any solutions which work in all browsers and don't use flash.

我想要一个按钮来选择文本区域中的文本并将其复制到剪贴板。我似乎找不到任何适用于所有浏览器的解决方案,而且不使用flash。

Surely this is doable? I've seen it all over the place but I guess they use flash, which I really want to stay away from if possible as some people don't have it.

当然这是可行的吗?我到处都见过,但是我猜他们用的是flash,如果可能的话,我真的想远离它,因为有些人没有flash。

This is what I have so far - it just selects the text:

这是我到目前为止得到的-它只选择文本:

function copyCode() {
  $("#output-code").focus();
  $("#output-code").select();
}

(The focus is not strictly necessary)

(重点不是必须的)

5 个解决方案

#1


55  

execCommand('copy')

There is a very new option. It is cross-browser but it will take time until everyone has updated their browser.

有一个非常新的选择。它是跨浏览器的,但它将需要时间,直到每个人都更新了他们的浏览器。

It works by using the document.execCommand('copy'); function. With this function you'll copy the select text. This will not only work with textareas but with every selected text on the webpage (like in span, p, div, etc.).

它使用document.execCommand('copy');函数。使用这个函数,您将复制select文本。这不仅适用于文本区域,还适用于网页上的每个选定文本(如span、p、div等)。

Available in Internet Explorer 10+, Chrome 43+, Opera 29+ and Firefox 41+ (see execCommand compatibility here).

可以在Internet Explorer 10+、Chrome 43+、Opera 29+和Firefox 41+中使用(参见execCommand兼容性)。

Example

// Setup the variables
var textarea = document.getElementById("textarea");
var answer  = document.getElementById("copyAnswer");
var copy    = document.getElementById("copyBlock");
copy.addEventListener('click', function(e) {

   // Select some text (you could also create a range)
   textarea.select(); 

   // Use try & catch for unsupported browser
   try {

       // The important part (copy selected text)
       var ok = document.execCommand('copy');

       if (ok) answer.innerHTML = 'Copied!';
       else    answer.innerHTML = 'Unable to copy!';
   } catch (err) {
       answer.innerHTML = 'Unsupported Browser!';
   }
});
<textarea id="textarea" rows="6" cols="40">
Lorem ipsum dolor sit amet, eamsemper maiestatis no.
</textarea><br/>

<button id="copyBlock">Click to copy</button> <span id="copyAnswer"></span>
   

#2


18  

You must use the Flash add-in you do not want to use to automatically copy text to the client's clipboard. A website automatically modifying the client's clipboard without the aid of active-x components is a security concern. Note that active-x components are programs that run on the user's machine and, technically, require the user's consent to be installed. Considering that the Clipboard is an operating system component, be happy that web browsers don't allow websites to highjack it by default.

您必须使用不想使用的Flash外接程序来自动将文本复制到客户端的剪贴板。一个网站在没有主动-x组件的帮助下自动修改客户的剪贴板是一个安全问题。注意,active-x组件是在用户机器上运行的程序,从技术上讲,需要用户的同意才能安装。考虑到剪贴板是一个操作系统组件,web浏览器不允许网站默认劫持它。

If the user does not have Flash, has Flash disabled, or has active-x disabled, then he or she probably is paranoid about security and doesn't want you messing with his or her keyboard anyway. At that point, the user would be used to not having much automatic or script-based functionality in websites. It's best to not try to openly defy the wishes of the end user.

如果用户没有Flash,没有Flash,或者没有active-x,那么他或她很可能对安全性非常担心,而且也不希望你乱用他或她的键盘。到那时,用户将习惯于在网站上没有很多自动的或基于脚本的功能。最好不要公然违背最终用户的意愿。

Please refer to the following Stack Overflow links:

请参考下面的堆栈溢出链接:

  1. How do I copy to the clipboard in JavaScript?
  2. 如何用JavaScript复制到剪贴板?
  3. Cross Browser Flash Detection in Javascript
  4. Javascript中的跨浏览器Flash检测

The ultimate answer there is to use Zero Clipboard, which is a library that uses a small, invisible Flash movie and JavaScript to use clipboard functionality like you are wanting. The library is available here: https://github.com/zeroclipboard/zeroclipboard The second link shows how to detect if Flash is disabled or not installed, which allows you to display a warning message like you would for JavaScript.

最终的解决方案是使用零剪贴板,这是一个库,它使用一个小的、不可见的Flash动画和JavaScript来使用剪贴板功能,就像您想要的那样。这个库在这里是可用的:https://github.com/zeroclipboard/zeroclipboard第二个链接显示了如何检测Flash是否被禁用或没有被安装,这允许您像显示JavaScript一样显示一个警告消息。

#3


9  

Now we have Clipboard.js by @zenorocha

现在我们有剪贴板。js的@zenorocha

To use it, download and call the script on your page.html (or install with bower or npm)

要使用它,请下载并调用页面上的脚本。html(或安装有bower或npm)

<script src="path_to_script/clipboard.min.js"></script>

Instantiate a new trigger on your script.js

在script.js上实例化一个新的触发器

new Clipboard('.trigger');

And go there to see some examples of usage: http://zenorocha.github.io/clipboard.js/#usage

然后去那里看看一些用法示例:http://zenorocha.github.io/clipboard.js/#usage

#4


6  

function copyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;  
    textArea.style.width = '2em';
    textArea.style.height = '2em'; 
    textArea.style.padding = 0;  
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';   
    textArea.style.background = 'transparent';
    textArea.value = text;
    textArea.id = 'ta';
    document.body.appendChild(textArea);
    //textArea.select();
    var range = document.createRange();
    range.selectNode(textArea);
    textArea.select();
    window.getSelection().addRange(range);
    try {
        var successful = document.execCommand('copy');
    } catch (err) {
         alert('Oops, unable to copy');
    }
    document.body.removeChild(textArea);
    return successful;
}

I Hope this is helpfull

我希望这对你有帮助

#5


1  

This is a pretty late response but for those searching in the future and having trouble with implementing the execCommand('copy') event to work for both desktop and mobile devices.

这是一个很晚的响应,但是对于那些在将来进行搜索的人来说,在执行execCommand('copy')事件时,在桌面和移动设备上都有麻烦。

Cross browser, Mobile friendly and No need to have outside sources or programs

跨浏览器,移动友好,不需要外部资源或程序

function CopyString(){
    var StringToCopyElement = document.getElementById('YourId');
    StringToCopyElement.select();

    if(document.execCommand('copy')){
        StringToCopyElement.blur();     
    }else{
        CopyStringMobile();
    }
}

function CopyStringMobile(){
    document.getElementById("YourId").selectionStart = 0;
    document.getElementById("YourId").selectionEnd = 999;
    document.execCommand('copy');

    if (window.getSelection) {
      if (window.getSelection().empty) {  // Chrome
        window.getSelection().empty();
      } else if (window.getSelection().removeAllRanges) {  // Firefox
        window.getSelection().removeAllRanges();
      }
    } else if (document.selection) {  // IE?
      document.selection.empty();
    }
}

Set the CopyString() function to a click event on whatever you're looking to fire the event. This is available to be used on both mobile and desktop operating systems.

将CopyString()函数设置为在要触发事件的任何对象上的单击事件。这可以在移动和桌面操作系统上使用。

Explanation

解释

You need to have two different ways of going about selecting the string to copy because as of today, the method for doing so via desktop will not work for mobile devices. I have an if then function to catch if the desktop method worked and if not, to fire the code that will work for a mobile device. This method requires no downloads or links needed. Both methods highlight the text you're looking to copy then fires the copy command to your clipboard, being followed by un-selecting the string you're attempting to copy. You can mix up the code to your liking but this is the way of doing so.

您需要有两种不同的方式来选择要复制的字符串,因为到目前为止,通过桌面进行选择的方法在移动设备上是行不通的。我有一个if函数来捕获桌面方法是否有效,如果无效,则触发用于移动设备的代码。此方法不需要下载或链接。这两个方法都突出显示要复制的文本,然后将复制命令发送到剪贴板,然后取消选择要复制的字符串。您可以根据自己的喜好混合代码,但这是实现的方式。

#1


55  

execCommand('copy')

There is a very new option. It is cross-browser but it will take time until everyone has updated their browser.

有一个非常新的选择。它是跨浏览器的,但它将需要时间,直到每个人都更新了他们的浏览器。

It works by using the document.execCommand('copy'); function. With this function you'll copy the select text. This will not only work with textareas but with every selected text on the webpage (like in span, p, div, etc.).

它使用document.execCommand('copy');函数。使用这个函数,您将复制select文本。这不仅适用于文本区域,还适用于网页上的每个选定文本(如span、p、div等)。

Available in Internet Explorer 10+, Chrome 43+, Opera 29+ and Firefox 41+ (see execCommand compatibility here).

可以在Internet Explorer 10+、Chrome 43+、Opera 29+和Firefox 41+中使用(参见execCommand兼容性)。

Example

// Setup the variables
var textarea = document.getElementById("textarea");
var answer  = document.getElementById("copyAnswer");
var copy    = document.getElementById("copyBlock");
copy.addEventListener('click', function(e) {

   // Select some text (you could also create a range)
   textarea.select(); 

   // Use try & catch for unsupported browser
   try {

       // The important part (copy selected text)
       var ok = document.execCommand('copy');

       if (ok) answer.innerHTML = 'Copied!';
       else    answer.innerHTML = 'Unable to copy!';
   } catch (err) {
       answer.innerHTML = 'Unsupported Browser!';
   }
});
<textarea id="textarea" rows="6" cols="40">
Lorem ipsum dolor sit amet, eamsemper maiestatis no.
</textarea><br/>

<button id="copyBlock">Click to copy</button> <span id="copyAnswer"></span>
   

#2


18  

You must use the Flash add-in you do not want to use to automatically copy text to the client's clipboard. A website automatically modifying the client's clipboard without the aid of active-x components is a security concern. Note that active-x components are programs that run on the user's machine and, technically, require the user's consent to be installed. Considering that the Clipboard is an operating system component, be happy that web browsers don't allow websites to highjack it by default.

您必须使用不想使用的Flash外接程序来自动将文本复制到客户端的剪贴板。一个网站在没有主动-x组件的帮助下自动修改客户的剪贴板是一个安全问题。注意,active-x组件是在用户机器上运行的程序,从技术上讲,需要用户的同意才能安装。考虑到剪贴板是一个操作系统组件,web浏览器不允许网站默认劫持它。

If the user does not have Flash, has Flash disabled, or has active-x disabled, then he or she probably is paranoid about security and doesn't want you messing with his or her keyboard anyway. At that point, the user would be used to not having much automatic or script-based functionality in websites. It's best to not try to openly defy the wishes of the end user.

如果用户没有Flash,没有Flash,或者没有active-x,那么他或她很可能对安全性非常担心,而且也不希望你乱用他或她的键盘。到那时,用户将习惯于在网站上没有很多自动的或基于脚本的功能。最好不要公然违背最终用户的意愿。

Please refer to the following Stack Overflow links:

请参考下面的堆栈溢出链接:

  1. How do I copy to the clipboard in JavaScript?
  2. 如何用JavaScript复制到剪贴板?
  3. Cross Browser Flash Detection in Javascript
  4. Javascript中的跨浏览器Flash检测

The ultimate answer there is to use Zero Clipboard, which is a library that uses a small, invisible Flash movie and JavaScript to use clipboard functionality like you are wanting. The library is available here: https://github.com/zeroclipboard/zeroclipboard The second link shows how to detect if Flash is disabled or not installed, which allows you to display a warning message like you would for JavaScript.

最终的解决方案是使用零剪贴板,这是一个库,它使用一个小的、不可见的Flash动画和JavaScript来使用剪贴板功能,就像您想要的那样。这个库在这里是可用的:https://github.com/zeroclipboard/zeroclipboard第二个链接显示了如何检测Flash是否被禁用或没有被安装,这允许您像显示JavaScript一样显示一个警告消息。

#3


9  

Now we have Clipboard.js by @zenorocha

现在我们有剪贴板。js的@zenorocha

To use it, download and call the script on your page.html (or install with bower or npm)

要使用它,请下载并调用页面上的脚本。html(或安装有bower或npm)

<script src="path_to_script/clipboard.min.js"></script>

Instantiate a new trigger on your script.js

在script.js上实例化一个新的触发器

new Clipboard('.trigger');

And go there to see some examples of usage: http://zenorocha.github.io/clipboard.js/#usage

然后去那里看看一些用法示例:http://zenorocha.github.io/clipboard.js/#usage

#4


6  

function copyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;  
    textArea.style.width = '2em';
    textArea.style.height = '2em'; 
    textArea.style.padding = 0;  
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';   
    textArea.style.background = 'transparent';
    textArea.value = text;
    textArea.id = 'ta';
    document.body.appendChild(textArea);
    //textArea.select();
    var range = document.createRange();
    range.selectNode(textArea);
    textArea.select();
    window.getSelection().addRange(range);
    try {
        var successful = document.execCommand('copy');
    } catch (err) {
         alert('Oops, unable to copy');
    }
    document.body.removeChild(textArea);
    return successful;
}

I Hope this is helpfull

我希望这对你有帮助

#5


1  

This is a pretty late response but for those searching in the future and having trouble with implementing the execCommand('copy') event to work for both desktop and mobile devices.

这是一个很晚的响应,但是对于那些在将来进行搜索的人来说,在执行execCommand('copy')事件时,在桌面和移动设备上都有麻烦。

Cross browser, Mobile friendly and No need to have outside sources or programs

跨浏览器,移动友好,不需要外部资源或程序

function CopyString(){
    var StringToCopyElement = document.getElementById('YourId');
    StringToCopyElement.select();

    if(document.execCommand('copy')){
        StringToCopyElement.blur();     
    }else{
        CopyStringMobile();
    }
}

function CopyStringMobile(){
    document.getElementById("YourId").selectionStart = 0;
    document.getElementById("YourId").selectionEnd = 999;
    document.execCommand('copy');

    if (window.getSelection) {
      if (window.getSelection().empty) {  // Chrome
        window.getSelection().empty();
      } else if (window.getSelection().removeAllRanges) {  // Firefox
        window.getSelection().removeAllRanges();
      }
    } else if (document.selection) {  // IE?
      document.selection.empty();
    }
}

Set the CopyString() function to a click event on whatever you're looking to fire the event. This is available to be used on both mobile and desktop operating systems.

将CopyString()函数设置为在要触发事件的任何对象上的单击事件。这可以在移动和桌面操作系统上使用。

Explanation

解释

You need to have two different ways of going about selecting the string to copy because as of today, the method for doing so via desktop will not work for mobile devices. I have an if then function to catch if the desktop method worked and if not, to fire the code that will work for a mobile device. This method requires no downloads or links needed. Both methods highlight the text you're looking to copy then fires the copy command to your clipboard, being followed by un-selecting the string you're attempting to copy. You can mix up the code to your liking but this is the way of doing so.

您需要有两种不同的方式来选择要复制的字符串,因为到目前为止,通过桌面进行选择的方法在移动设备上是行不通的。我有一个if函数来捕获桌面方法是否有效,如果无效,则触发用于移动设备的代码。此方法不需要下载或链接。这两个方法都突出显示要复制的文本,然后将复制命令发送到剪贴板,然后取消选择要复制的字符串。您可以根据自己的喜好混合代码,但这是实现的方式。