复制文本到剪贴板,仅限火狐浏览器,无需插件。

3

我想点击一个按钮,将<div id="content">内的文本复制到剪贴板中。有没有一种不使用插件的javascript或jquery方法可以实现这一点。我不需要跨浏览器支持,只需要在Firefox上实现即可。

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

可能是如何在JavaScript中复制到剪贴板?的重复问题。 - peirix
4个回答

1

工作直到大约2012年11月,然后Mozilla通过一次更新摧毁了它。现在我有一个解决方法:打开新窗口并复制其中的内容。

感谢Matthew Flaschen提出的DataURL想法(https://dev59.com/wHA65IYBdhLWcg3wuhIR#3665147

/**
*   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;
}

0

0

0

在HTML5之前,没有可行的方法。但即便在现在,实现也很棘手。所有的插件都使用Flash来复制到剪贴板。您可以使用zClip http://www.steamdev.com/zclip/

正如gion_13所说,他提到的方法也需要使用Flash,正如链接中所示。因此,使用一个小型插件来复制到剪贴板是无害的 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接