Copy / Put text on the clipboard with FireFox, Safari and Chrome

In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?


There is now a way to easily do this in most modern browsers using

document.execCommand('copy');

This will copy currently selected text. You can select a textArea or input field using

document.getElementById('myText').select();

To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.

For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.

A full example would look like

<html>
<head>
    <title>copy test</title>
</head>
<body>
    <button onclick="copier()">Copy</button>
    <textarea id="myText">Copy me PLEASE!!!</textarea>

    <script>
        function copier(){
            document.getElementById('myText').select();
            document.execCommand('copy');
        }
    </script>
</body>
</html>

For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around available using Flash.

function copyIntoClipboard(text) {

    var flashId = 'flashId-HKxmj5';

    /* Replace this with your clipboard.swf location */
    var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';

    if(!document.getElementById(flashId)) {
        var div = document.createElement('div');
        div.id = flashId;
        document.body.appendChild(div);
    }
    document.getElementById(flashId).innerHTML = '';
    var content = '<embed src="' + 
        clipboardSWF +
        '" FlashVars="clipboard=' + encodeURIComponent(text) +
        '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashId).innerHTML = content;
}

The only disadvantage is that this requires Flash to be enabled.

source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is it's Google cache)


Online Spreadsheets hook Ctrl+C, Ctrl+V events and transfer focus to a hidden TextArea control and either set its contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.

see also Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?

链接地址: http://www.djcxy.com/p/3322.html

上一篇: 将字符串作为文本/ html复制到剪贴板

下一篇: 使用FireFox,Safari和Chrome在剪贴板上复制/放置文本