views:

30069

answers:

9

What is the best way to copy text to the clipboard? (multi-browser)

I have tried:

function copyToClipboard(text)
{
    if (window.clipboardData) // IE
    {  
        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 gives a syntax error. In Firefox it says "unsafeWindow is not defined".

A: 

As far as I know that only works in IE.

But some googling I stubmled upon this page but it requires the user to change the configuration first and even then it doesn't seems to work.

Stormenet
+4  A: 

Reading and modifying the clipboard from a webpage raises security and privacy concerns. However in internet explorer it is possible to do it. I found this example snippet:

<script type=”text/javascript”>
function select_all(obj) {
  var text_val=eval(obj);
  text_val.focus();
  text_val.select();
  if (!document.all) return; // IE only
  r = text_val.createTextRange();
  r.execCommand(\\’copy\\’);
}</script>
<input value=”http://www.sajithmr.com”
 onclick=”select_all(this)” name=”url” type=”text” />
bandi
+6  A: 

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

Quog
This is outdated now... check out the suggestion by GvS
fudgey
The suggestion by GvS uses a flash movie? Isn't that the same idea?
TheImirOfGroofunkistan
+10  A: 

With the following workaround, it will work in both IE and FireFox (tried and tested):

First, download this swf file: http://www.webtips.co.in/postimg/clipboard.rar

Then, use the following function to add text to the client's Clipboard:

function copy_to_clipboard(text)  
  {  
      if(window.clipboardData)  
      {  
      window.clipboardData.setData('text',text);  
      }  
      else  
      {  
          var clipboarddiv=document.getElementById('divclipboardswf');  
      if(clipboarddiv==null)  
      {  
         clipboarddiv=document.createElement('div');  
             clipboarddiv.setAttribute("name", "divclipboardswf");  
         clipboarddiv.setAttribute("id", "divclipboardswf");  
         document.body.appendChild(clipboarddiv);  
      }  
          clipboarddiv.innerHTML='<embed src="clipboard.swf" FlashVars="clipboard='+  
  encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';  
      }  
      alert('The text is copied to your clipboard...');  
      return false;  
  }

Reference: http://www.webtips.co.in/javascript/copy-to-clipboard-with-javascript-on-mozilla-firefox-and-ie.aspx

Andreas Grech
I have tried and tried this code and similar code, and it just does not work. It doesn't work for me in FF3, and it doesn't work for me in Google Chrome 1.5. I sure wish it did, though.
Elmo Gallen
I've heard this doesn't work in Flash 10.
Greg Dean
This approach will fail until Flash 10.
Nicholas Kreidberg
Yep, this no longer works in non-IE browsers if Flash 10 is installed :(
Alex
BTW see http://code.google.com/p/zeroclipboard/ for a working multi-browser solution
Alex
Seems like the other answer with tons of votes should be the accepted answer ...
Travis
links are dead, update please
Andrija
+2  A: 

The other methods will copy plain text to the clipboard. To copy HTML (ie, you can paste results into a WSIWYG editor), you can do the following in IE ONLY. This is is fundamentally different from the other methods, as the browser actually visibly selects the content.

// create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
    contentEditable = true;
}     
editableDiv.appendChild(someContentElement);          

// select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();  
r.execCommand("Copy");

// deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();
Chase Seibert
+1  A: 

Looks like you took the code from Greasemonkey\JavaScript Copy to Clipboard button or the original source of this snippet...

This code was for Greasemonkey, hence the unsafeWindow. And I guess the syntax error in IE comes from the const keyword which is specific to Firefox (replace it with var).

PhiLho
+47  A: 

Best answer solution doesn't work in Flash 10, but there is very nice library that works great:

http://code.google.com/p/zeroclipboard/

GvS
great, thank you.
Sepehr Lajevardi
too bad it requires flash.
neoneye
@GvS: thank you for posting this
Alberto Zaccagni
+3  A: 

As of Flash 10, you can only copy to clipboard if the action originates from user interaction with a Flash object. (Read related section from Adobe's Flash 10 announcement)

Zero Clipboard is currently the only library that tries to solve this, by overlaying a Flash object above the Copy button, or whatever element initiates the copy. The current problem with Zero Clipboard is that it uses absolute positioning on the viewport, which breaks when the page is resized. It would be more natural if Zero Clipboard did a 100% height/width overlay inside the wrapper that caught the event.

matthuhiggins
+1  A: 

If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box then Clippy is a nice alternative to some of the more complex ones above.

http://github.com/mojombo/clippy

It's the same copy solution used but Github. Example Flash embed code below:

<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>
Brent M