preface
Sometimes we want access to the user’s clipboard for user-friendly features. On the other hand, the data in the clipboard is very private to the user, so the browser has security restrictions on access to the information and also provides access interfaces.
Some time ago, due to the service function, it is necessary to implement when users paste in rich text, if the user copied a picture, you need to upload the picture to the server and insert it into the text. Seemingly reasonable request, but there are many holes
When can I access the clipboard
1. When a user triggers an onPaste event (only the user can trigger the event), obtain the value from the event object. The official documentation
let text = (event.clipboardData || window.clipboardData).getData('text');
Copy the code
2, Chrome added a new asynchronous clipboard API, you can apply for access from the user, after getting permission to access. Refer to an article by Zhihu
Access the images in the clipboard
Say first conclusion
Copy images from the file system | MAC OS gets the last card; Windows can’t get the data |
---|---|
screenshots | MAC and Windows can be obtained |
Copy in the browser interface | MAC and Windows can be obtained |
Why Windows can’t get a copy of it, the user in the file system copy of the file, in the clipboard is not the image (guess is the image of the tag), so it is not available.
The following code
/** * triggers the paste event and responds to the method */
function paste(event) {
// Get the data
let items = (event.clipboardData || event.originalEvent.clipboardData).items;
let imgList = [];
let strList = [];
for (let item of items) {
// If the data is a file
if (item.kind === 'file') {
let blob = item.getAsFile();
let reader = new FileReader();
blobList.push(blob);
reader.onload = (a)= > {
imgList.push(reader.result);
}
reader.readAsDataURL(blob);
} else if(item.kind === 'string') {
// If the data is a string
item.getAsString((s) = >{ strList.push(s); }); }}}Copy the code
Finally, to fully implement the user Contr+C, Contr+V to post, it is not yet possible. There is an alternative, which is also convenient and supported by all browsers, to drag an image to a rich text area.
There is another commercial product from a company whose browser plug-in allows you to copy images from your desktop and paste them into your browser. Unfortunately, it’s currently only available on Windows, not MAC OS.
My guess is that once you install the browser plugin and allow it to run, when you trigger the paste event in the browser, the JS calls the plugin method, the plugin accesses the file in the system (the plugin is actually a Piece of Windows software, so it can access the file system), and then returns it to the JS of the page.