Due to browser privacy protocols, the clipboard was previously inaccessible to browsers. In recent years, with the rise of Web applications, the W3C has been expanding JavaScript applications to include clipboards directly from the front end. According to the way of access, the article is divided into indirect access and direct access.
Indirect access
Interaction events
User interaction events, such as paste, cut, and dragstart, are accessible to the clipboard through the Event object. This section allows you to format and customize the clipboard content. In contenteditable (editable) elements, to unify the pasting text style, we can filter the text format in the element’s copy event.
let editor = document.getElementById('editor)
editor.addEventListener('paste', e => { e.preventDefault() let data = e.clipboardData.getData('text/plainData = data.replace(/>/g, ')>') .replace(/<') let result = data.split('/n').join('<br />') document.execCommand('insertHTML', null, result)
})
Copy the code
Can we get anything other than text? Like images? The answer is half and half. Why say half and half? Normally, we use the screenshot software to capture the screenshot, which can be obtained in e.datatransfer. files. The screenshot software actually puts the Base64 file into the clipboard. However, if you copy an image in the operating system, you cannot retrieve it in the dataTransfer object. This is a browser privacy protocol limitation, just as web pages cannot operate directly on system files (although some browsers already support the File API).
In business development, testing children, always can give people some surprises, who said only paste, I can also drag, drag some strange content into, look, found a Bug. Editable elements allow drag and drop by default. To avoid this, we are given only two options: first, forbid drag, which is ok, but violent, and second, overwrite drag and listen for dragstart events.
let editor = document.getElementById('editor)
editor.addEventListener('dragstart', E => {e.preventDefault() // Get the page selected text let selection = window.getSelection() let data = selection.toString() e.dataTransfer.setData('text/plain', data)
})
Copy the code
Direct access to the
clipboard API
Recently, Navigator has added Clipboard API, which can not only read Clipboard text and files, but also provide write operations, but the compatibility is poor. Text reading and writing is supported in Chrome 66, but image/ PNG requires 76+. The return value is Promise, which is convenient to use. However, to access the clipboard, you need to run it in the HTTPS service page first, and then request user authorization. After authorization is granted, the clipboard can be accessed. The basic usage example is as follows:
// Read text
navigator.clipboard.readText().then(
clipText= > document.getElementById("editor").innerText = clipText
);
// Read the clipboard image
navigator.permissions.query({name: "clipboard-read"}).then(result= > {
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.read().then(data= > {
for (let i=0; i<data.items.length; i++) {
if(data.items[i].type ! ="image/png") {
alert("Clipboard contains non-image data. Unable to access it.");
} else {
const blob = data.items[i].getType("image/png"); imgElem.src = URL.createObjectURL(blob); }}}); }});Copy the code
electron clipboard
Electron is now being incorporated into desktop application development by more and more companies. Since the clipboard operation has always been a pain point in Web application development, in Electron, both the main process and the renderer process can use the clipboard API, and the operation is much richer. It can operate not only text, files, but also Buffer, making many operations possible.
const { clipboard } = require('electron')
clipboard.writeText('hello i am a bit of text! ')
const text = clipboard.readText()
console.log(text)
Copy the code
The resources
- navigator clipboard
- electron clipboard