Writing in the front

Product MM: I think there is a button on the page, click it and copy a link to the system clipboard.

Development GG: No problem

  • 1 introductionclipboard.js
<script 
    type="text/javascript" 
    src="script/clipboard.min.js">
</script>
Copy the code
  • 2 Create a file with.btnThe button (or other) element of the class that specifies the text to copy
<body>
    <button 
        class="btn" 
        data-clipboard-text="http://www.jq22.com/">Click on the copy</button>
</body>
Copy the code
  • instantiate
<! Instantiate the clipboard at the bottom of the page, initialize the copy action on the.btn element -->
<script type="text/javascript">  
    window.onload = function() {  
        var clipboard = new Clipboard('.btn');  
    }  
</script>
Copy the code

All in one go

Product MM: @ development GG 666, what is the realization principle of this thing?

Developed GG: en…. No… Know… + _ +

How does copying text to a clipboard work?

1, use,documentThe object’sexecCommandMethod to implement copy

document.execCommand('copy')
Copy the code

The documentation on MDN describes it this way: When an HTML document switches to design mode, the document exposes the execCommand method, which allows commands to be run to manipulate elements in the editable content area.

Come and go, the realization idea is as follows:

  • 1 Manually create an editable element, such as textarea, and set the Value to be copied to its Value

  • 2 Insert the Textarea into the page and call the Select () method of the textarea to check the value

  • Note that the textarea style is not visible (use the style to remove it from the visible area).

  • 4 call document. ExecCommand (‘ copy ‘)

  • 5 After the implementation is copied to the clipboard, the generated secondary node (Textarea) is removed

The relevant code

function copy2clipboard(copyText) {
    //1 Manually create editable elements such as textarea,
    var textArea = document.createElement('textarea');
    //2 Then set the Value to be copied to its Value
    textArea.value = copyText
    // Insert the textarea into the page
    document.body.appendChild(textArea)
    // Call the select() method of textarea to select the value
    textArea.select();
    // 3 Textarea to set the style to invisible (use the style to move it out of the visual area)
    textArea.style.position = 'fixed';
    textArea.style.top = '-9999px';
    textArea.style.left = '-9999px';
    // 4 Call document.execCommand('copy')
    document.execCommand('copy')/ / copy
    / / document. ExecCommand (' cut ') / / shear
}
Copy the code

advantages

Good compatibility and easy operation

disadvantages

1. Only the selected content can be copied to the clipboard, but no content can be written to the clipboard

2, it is synchronous operation, if copy/paste a large amount of data, the page will appear to stall. Some browsers also pop up a box asking for permission, and the page stops responding before the user makes a choice

2. Use the latest API implementationnavigator.clipboardobject

The navigator. The clipboard MDN address

function copy2clipboard(text) {
    navigator.clipboard.writeText(text)
      .then(function () {
          console.log('success')},function (e) {
          console.log(e)
          console.log('fail')}); }Copy the code

advantages

Support for Promise, support for writing files, images, etc to clipboard…

disadvantages

Chrome specifies that only HTTPS pages can use this API, but localhost does

2. The user’s permission must be explicitly obtained when calling

3. Compatibility may not be that good

Navigator.clipboard advanced usage

Save an image to the clipboard

function setHtmlToClipboard(text) {
  navigator.permissions.query({ name: 'clipboard-write' }).then(async (result) => {
        if (result.state === 'granted') {
            // Copy some text
            // var blob = new Blob(['<p>... paragraph ...</p>'], { type: 'text/plain' });
            // var item = new ClipboardItem({ 'text/plain': blob });
            const imgURL = 'https://dummyimage.com/300.png';
            const data = await fetch(imgURL);
            const blob = await data.blob();
            var item = new ClipboardItem({
                [blob.type]: blob
            })
            navigator.clipboard.write([item]).then(function () {
                console.log("Copied to clipboard successfully!");
            }, function (error) {
                console.error("unable to write to clipboard. Error:");
                console.log(error);
            });
        } else {
            console.log("clipboard-permissoin not granted: "+ result); }}); }Copy the code

Reference link address

Ruan Yifeng big man’s blog

Document. ExecCommand MDN address

The navigator. The clipboard MDN address

Clipboard.js => Copy the text

Select => select text of an element node