【问题标题】:Copy to Clipboard for all Browsers using javascript使用 javascript 复制到所有浏览器的剪贴板
【发布时间】:2011-10-10 13:04:21
【问题描述】:

我试图让“复制到剪贴板”在所有浏览器上都能正常工作,但没有成功。

我正在使用 javascript,我不想使用 Zero Clipboard 来做。

请告诉我们我的代码有什么问题。

感谢您的帮助。

下面是代码(目前我的代码只在IE浏览器上运行):-

<script type="text/javascript">
function copyToClipboard(s)
{
    if( window.clipboardData && clipboardData.setData )
    {
        clipboardData.setData("Text", s);
    }
    else
    {
        // You have to sign the code to enable this or allow the action in about:config by changing
        user_pref("signed.applets.codebase_principal_support", true);
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

        var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;

        // create a transferable
        var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;

        // specify the data we wish to handle. Plaintext in this case.
        trans.addDataFlavor('text/unicode');

        // To get the data from the transferable we need two new objects
        var str = new Object();
        var len = new Object();

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

        var copytext=meintext;

        str.data=copytext;

        trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

        var clipid=Components.interfaces.nsIClipboard;

        if (!clip) return false;

        clip.setData(trans,null,clipid.kGlobalClipboard);      
    }
}
</script>

<textarea id='testText' rows="10" cols="100">Enter your Sample text</textarea><br />
<button onclick="copyToClipboard(document.getElementById('testText').value);" >clipboard</button><br /><br />
<textarea rows="10" cols="100">Paste your text here</textarea><br />

【问题讨论】:

  • 据我所知,firefox中默认不能使用js访问剪贴板。唯一通用的方式是flash,而不是js。
  • @Rufus:但就我而言,我需要不使用 flash。
  • @SivaCharan 那很抱歉,你得请你的访问者更改他们的firefox设置,在about:config中进行一些修改。
  • @JohnKeyes:我不想使用闪存。实际上我已经提到了这个现有的问题,但大多数人给出的解决方案是只使用闪存。但就我而言,我不能使用闪光灯来做到这一点。我想实现为 javascript。如果有任何想法,请告诉我。

标签: javascript clipboard


【解决方案1】:

这适用于 firefox 3.6.x 和 IE:

    function copyToClipboardCrossbrowser(s) {           
        s = document.getElementById(s).value;               

        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }           
        else
        {
            // You have to sign the code to enable this or allow the action in about:config by changing
            //user_pref("signed.applets.codebase_principal_support", true);
            netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

            var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;

            // create a transferable

            var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;

            // specify the data we wish to handle. Plaintext in this case.
            trans.addDataFlavor('text/unicode');

            // To get the data from the transferable we need two new objects
            var str = new Object();
            var len = new Object();

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

            str.data= s;        

            trans.setTransferData("text/unicode",str, str.data.length * 2);

            var clipid=Components.interfaces.nsIClipboard;              
            if (!clip) return false;
            clip.setData(trans,null,clipid.kGlobalClipboard);      
        }
    }

【讨论】:

  • 哇!这行得通!但是通过调用诸如“Components.classes['@mozilla.org/widget/transferable;1']”之类的东西,我们会去 Mozilla 网站吗?
  • 这在最新版本的 Firefox 中不起作用,其中不推荐使用 Components
  • !我们需要所有浏览器通用的东西!!! , com'on 浏览器...你在哪里。你们会让 IE 在这方面打败你们吗?!
  • 图像数据应该使用什么? (顺便说一句,你们注意到@ravz 在他的评论中通知自己了吗?)
【解决方案2】:

我也花了很多时间寻找解决这个问题的方法。这是我迄今为止发现的:

如果您希望您的用户能够点击按钮并复制一些文本,您可能必须使用 Flash。

如果您希望您的用户在页面上的任意位置按 Ctrl+C,但始终将 xyz 复制到剪贴板,我在 YUI3 中编写了一个全 JS 解决方案(尽管它可以很容易地移植到其他框架或原始 JS,如果你感觉特别自我厌恶)。

它涉及在屏幕外创建一个文本框,一旦用户按下 Ctrl/CMD,该文本框就会突出显示。当他们不久之后点击“C”时,他们复制了隐藏的文本。如果他们点击“V”,他们会在粘贴事件触发之前被重定向到一个容器(您选择的)。

此方法可以很好地工作,因为当您在正文中的任何位置侦听 Ctrl/CMD 按键时,“A”、“C”或“V”按键侦听器仅附加到隐藏的文本框(而不是整个身体)。 它也不必打破用户的期望 - 如果您没有选择任何要复制的内容,您只会被重定向到隐藏框!

这是我在我的网站上所做的工作,但如果有任何更新,请查看 http://at.cg/js/clipboard.js 以获取更新:

YUI.add('clipboard', function(Y) {


// Change this to the id of the text area you would like to always paste in to:

pasteBox = Y.one('#pasteDIV');


// Make a hidden textbox somewhere off the page.

Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');


// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:

// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
    copyData();
        //  Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
        //  alert(e.keyCode);
        //  }, 'body',  'down:', Y);
}, 'body',  'down:91,224,17', Y);

// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
    // Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
    // Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
    // Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
    pasteBox.select();
}, '#copyBox',  'down:86', Y);

// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
    // User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
    pasteBox.select();
}, '#copyBox',  'down:65', Y);



// What to do when keybindings are fired:

// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
    var txt = '';
    // props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
        if (window.getSelection) { txt = window.getSelection(); }
        else if (document.getSelection) { txt = document.getSelection(); }
        else if (document.selection) { txt = document.selection.createRange().text; }
        else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');

    // If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy. 
        if(txt=='') {
                copyBox.select();
        }
    // They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
        else if (txt == copyBox.get('value')) {
        alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
                copyBox.select();
        } else {
                // They also might have selected something completely different! If so, let them. It's only fair.
        }
}
});

希望其他人觉得这很有用:]

【讨论】:

  • 如果用户使用鼠标复制到剪贴板怎么办?要求 Ctrl / Cmd 击键似乎很脆弱。
【解决方案3】:

出于安全原因,大多数浏览器都不允许修改剪贴板(IE 除外,当然...)。

使复制到剪贴板功能跨浏览器兼容的唯一方法是使用 Flash。

【讨论】:

  • 使用copy 事件可以设置文本数据。如果不使用本机函数,则选择一些要复制的隐藏文本。
【解决方案4】:

我认为 zeroclipboard 很棒。此版本适用于最新的 Flash 11:http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution

【讨论】:

  • Asker 已经声明 ZeroClipboard 不是入门者。
猜你喜欢
  • 2012-12-07
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 2012-08-28
  • 2020-10-28
  • 1970-01-01
  • 2015-08-31
相关资源
最近更新 更多