Copy to clipboard without Flash

后端 未结 8 842
情深已故
情深已故 2020-11-28 05:28

I found many solutions for copying to the clipboard, but they all either with flash, or for websites side. I\'m looking for method copy to clipboard automatically, without f

相关标签:
8条回答
  • 2020-11-28 06:24

    You can use a clipboard local to the HTML page. This allows you to copy/cut/paste content WITHIN the HTML page, but not from/to third party applications or between two HTML pages.

    This is how you can write a custom function to do this (tested in chrome and firefox):

    Here is the FIDDLE that demonstrates how you can do this.

    I will also paste the fiddle here for reference.


    HTML

    <p id="textToCopy">This is the text to be copied</p>
    <input id="inputNode" type="text" placeholder="Copied text will be pasted here" /> <br/>
    
    <a href="#" onclick="cb.copy()">copy</a>
    <a href="#" onclick="cb.cut()">cut</a>
    <a href="#" onclick="cb.paste()">paste</a>
    

    JS

    function Clipboard() {
        /* Here we're hardcoding the range of the copy
        and paste. Change to achieve desire behavior. You can
        get the range for a user selection using
        window.getSelection or document.selection on Opera*/
        this.oRange = document.createRange();
        var textNode = document.getElementById("textToCopy");
        var inputNode = document.getElementById("inputNode");
        this.oRange.setStart(textNode,0);
        this.oRange.setEndAfter(textNode);
        /* --------------------------------- */
    }
    
    Clipboard.prototype.copy = function() {
        this.oFragment= this.oRange.cloneContents();
    };
    
    Clipboard.prototype.cut = function() {
        this.oFragment = this.oRange.extractContents();
    };
    
    Clipboard.prototype.paste = function() {
        var cloneFragment=this.oFragment.cloneNode(true)
        inputNode.value = cloneFragment.textContent;
    };
    
    window.cb = new Clipboard();
    
    0 讨论(0)
  • 2020-11-28 06:25

    document.execCommand('copy') will do what you want. But there was no directly usable examples in this thread without cruft, so here it is:

    var textNode = document.querySelector('p').firstChild
    var range = document.createRange()
    var sel = window.getSelection()
    
    range.setStart(textNode, 0)
    range.setEndAfter(textNode)
    sel.removeAllRanges()
    sel.addRange(range)
    document.execCommand('copy')
    
    0 讨论(0)
提交回复
热议问题