2011-09-19 125 views
3

我想單擊按鈕將<div id="content">中的文本複製到剪貼板。有沒有辦法做到這一點與JavaScript或jQuery,但沒有使用插件。我不需要它是跨瀏覽器的,只是在Firefox上。將文本複製到剪貼板,僅限Firefox,無插件

$('#copy').click(function(){ 
    var cont = $('#content').text(); 
    //how to copy cont to clipboar? 
}); 
+0

可能重複[如何複製在JavaScript到剪貼板?](http://stackoverflow.com/questions/400212/how-to -copy到剪貼板功能於JavaScript的) – peirix

回答

0

不,HTML5之前沒有辦法。但是實現這一點甚至非常棘手。所有的插件使用閃存複製到剪貼板。您可以使用zClip http://www.steamdev.com/zclip/

什麼gion_13所說的也需要閃光,因爲你可以注意到在文章中的鏈接。所以使用微小的插件複製到剪貼板是沒有害處的:)

1

工作到2012年11月左右,Mozilla通過更新銷燬它。現在我已經有了一個解決方法:打開帶有內容的新窗口進行復制。

感謝馬修·富蘭琛的DataURL想法(https://stackoverflow.com/a/3665147/1120146

/** 
* To use the clipboard from Mozilla/NS/Firefox: 
* 
* Clipboard access works only up to Firefox 14 :-((thanks to those security fanatics) 
* 
* Solution for later versions: Window pops up with text inside (data url) 
* 
* In "about:config" : 
*  set signed.applets.codebase_principal_support = true! 
* 
* @param text: The text which shold be copied to clipboard 
* @param fallbackContentType: The content type of the text, if clipboard access 
*        doesn't work, i.e. "text/csv" 
*        default: text/plain 
*/ 

function toClipboard(text, fallbackContentType) { 
    var success = false; 
    if (window.clipboardData) { 
      // the IE-manier 
     window.clipboardData.setData("Text", text); 
     success = true; 
    } 
    else if (window.netscape) { 

     if(netscape.security.PrivilegeManager != undefined) { 
      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); 

      var clip = Components.classes['@mozilla.org/widget/clipboard;1'].getService(Components.interfaces.nsIClipboard); 
      var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 

      if(typeof(clip) == "object" && typeof(trans) == "object") { 
       trans.addDataFlavor('text/unicode'); 

       var stingSupporter = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 

       stingSupporter.data = text; 
       trans.setTransferData("text/unicode", stingSupporter, text.length * 2); 
       var clipid = Components.interfaces.nsIClipboard; 
       clip.setData(trans, null, clipid.kGlobalClipboard); 

       success = true; 
      } 
     } 
     else { // Firefox > v15 
      // Create Data URL 
      if(fallbackContentType == undefined) fallbackContentType = "text/plain"; 

      var url = "data:"+ fallbackContentType +"," + encodeURIComponent(text); 
      window.open(url); 
     } 
    } 
    return success; 
}