Summary of how JavaScript reads and writes the clipboard

Although there are security issues in JavaScript operating the clipboard, it is still very convenient in some application scenarios, such as copying a
link
.
Mode 3. window.clipboardData object
Mode 4. Use some encapsulated third-party libraries

Method 1 and method 2 are native to the JavaScript language, and method 2 is a more traditional method. Although currently supported by various browsers, there are some shortcomings and deficiencies;
method 1 is the recommended method, because it appeared later. The browser version has certain requirements; Mode 3 is unique to the IE browser, and it is not supported in the Edge version; Mode 4 is to use some encapsulated clipboard components.

1. [Recommended method] Clipboard object of navigator

  1. All operations are asynchronous, return Promise objects, and will not cause page freezes
  2. Can put anything (including pictures) into the clipboard

basic use

  1. Get the Clipboard object, Clipboard is included in the navigator,
const clipboard = navigator.clipboard;

Returns undefined if the browser does not support it

  1. write content to clipboardnavigator.clipboard.writeText('写入的内容')

  2. Read content from the clipboard. navigator.clipboard.readText()
    When reading, the browser will pop up a window to confirm.
    Because the asynchronous return is used here, the method returns a Promise object. To get the clipboard content, you can get it in the then method.

        clipPromise.then(function(clipText){
            alert(clipText); // 剪贴板内容
        });
  1. Complete example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ClipBoard Demo</title>
<script type="text/javascript">
    function readClipText(){
        var clipPromise = navigator.clipboard.readText();
        clipPromise.then(function(clipText){
            alert(clipText);
        });

        
    }
 </script>
</head>
<body>
<input type="button" value="Clipboard-写数据" onclick="navigator.clipboard.writeText('123456')">
<input type="button" value="Clipboard-读数据" onclick="navigator.clipboard.readText().then(function(clipText){ alert(clipText);})">
<input type="button" value="Clipboard-读数据2" onclick="readClipText()">
</body>
</html>

limit

  1. Only HTTPS pages are supported in Chrome (except for local development localhost)
  2. Corresponding to read and write permissions. Write permissions are granted automatically, and read permissions require user consent. That is, when the code reads the clipboard data, a dialog box will pop up for the user to confirm.

Browser Compatible

insert image description here

2. [Deprecated] document.execCommand

The function is obsolete, although the function is normal in some browsers, it is not recommended because it may not be supported at any time.

  • The way to use it is to select the text first, and then call document.execCommand('copy')Copy to clipboard.
  • When pasting, use document.execCommand('paste')to output the contents of the clipboard to the currently focused element
document.execCommand('copy')
document.execCommand('cut')
document.execCommand('paste')

Complete example

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document clipboard</title>
<script type="text/javascript">
   function myDocClipboard(){
	   document.getElementById('myText').select();
      document.execCommand('copy');
   }
</script>
</head>
<body>
<input type="text" id="myText" value="123456"/>
<input type="button" value="document-剪切板" onclick="myDocClipboard()">
</body>
</html>

limit

  1. Only the selected content can be copied to the clipboard, not arbitrary content
  2. The operation is synchronous, if the amount of data is large, the page will be stuck

3. [IE-specific method] window.clipboardData object

In the IE browser, the window object has a clipboardData object, and the setData and getData of this object are used to set or get the value in the clipboard.
It works in IE 11, but no longer works in Microsoft Edge.

set clipboard content

window.clipboardData.setData('Text', '123456')

Get clipboard content

window.clipboardData.getData('Text')

test:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="IE剪切板-设置值" onclick="window.clipboardData.setData('Text', '123456')">
<input type="button" value="IE剪切板-获取值" onclick="alert(window.clipboardData.getData('Text'))">
</body>
</html>

4. [Other ways] Third-party libraries

In the early days, many third-party libraries used Flash to implement the clipboard function, but now many browsers do not provide support for Flash by default, and all such methods are naturally not recommended. Here is a good library:
clipboard https://github.com/zenorocha/clipboard.js

Lightweight, the entire library file is more than 3k, and does not depend on Flash.

The steps are also very simple:

  1. import library
  2. Create ClipboardJS object
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clipboard 库</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/clipboard.min.js"></script>
</head>
<body>
    <textarea id="bar">需要复制的内容</textarea>
    <button class="btn" data-clipboard-action="copy" data-clipboard-target="#bar">
        复制到剪切板
    </button>
    <script>
        var clipboard = new ClipboardJS('.btn');
    </script>

</body>
</html>

Guess you like

Origin blog.csdn.net/oscar999/article/details/124090065