The native method of copying/pasting in JavaScript

Source: Internet
Author: User

In IE 7 and earlier browsers, developers can only use flash plug-ins to implement this function because they do not have the ability to directly access the clipboard.

Currently, some browsers support the clipboard function, except Safari on Mac and iOS. However, different browsers have different levels of support, and some functions are incomplete or have defects. Therefore, there are many compatibility issues to consider. The user must manually trigger by clicking the mouse or pressing the button, and the script cannot manipulate the clipboard at any time.

The following describes the JavaScript syntax of the clipboard.

I. Clipboard events

Beforecopy: triggered before a copy operation occurs;
Copy: triggered when a copy operation occurs;
Beforecut: triggered before a cut operation occurs;
Cut: triggered when a cut operation occurs;
Beforepaste: triggered before the paste operation;
Paste: triggered when the paste operation occurs.
Before an actual event occurs, you can use the beforecopy, beforecut, and beforepaste events to modify data before sending data to the clipboard or obtaining data from the clipboard.

II. Access the clipboard data: clipboardData object

To access data in the clipboard, you can use the clipboardData object:

In IE, the clipboardData object is the property of the window object;
In Chrome, Safari, and Firefox 4 +, the clipboardData object is the attribute of the corresponding event object.
However, in Chrome, Safari, and Firefox 4 +, the clipboardData object is valid only when the clipboard event is being processed, to prevent unauthorized access to the clipboard; in IE, then you can access the clipboardData object at any time. To ensure cross-browser compatibility, it is best to use the clipboardData object only when a clipboard event occurs.

2.1 Methods for clipboardData objects:

 

GetData ()
SetData ()
ClearData ()
2.1.1 getData ()

The getData () method is used to obtain data from the clipboard. It receives a parameter, that is, the data format to be obtained.

In IE, there are two data formats: "text" and "URL ".
In Chrome, Safari, and Firefox 4 +, this parameter is a MIME type. However, you can use "text" to represent "text/plain ".
// Obtain the clipboard data
Function getClipboardText (event ){
Var clipboardData = event. clipboardData | window. clipboardData;
Return clipboardData. getData ("text ");
};
2.1.2 setData ()

The first parameter of the setData () method is also the data type, and the second parameter is the text to be placed in the clipboard.

For the first parameter, IE still supports "text" and "URL", while in Chrome and Safari, MIME types are still supported. However, unlike the getData () method, the setData () method in Chrome and Safari cannot recognize the "text" type.

After the text is successfully placed in the clipboard, this method returns true; otherwise, false.

// Set the clipboard data
Function setClipboardText (event, value ){
If (event. clipboardData ){
Return event. clipboardData. setData ("text/plain", value );
} Else if (window. clipboardData ){
Return window. clipboardData. setData ("text", value );
    }
};
2.2 attributes of a clipboardData object:

Attribute type description
DropEffect String is none by default.
EffectAllowed String is uninitialized by default.
Files FileList paste operation is empty List.
Data in the items DataTransferItemList clipboard.
Data type in the types Array clipboard.
2.2.1 items attributes:

Items is a DataTransferItemList object, which naturally contains data of the DataTransferItem type.

Attribute

The DataTransferItem of items has two attributes: kind and type:

Attribute description
Kind is generally string or file.
Type indicates the specific data Type, for example, which type of string or file is used, that is, MIME-Type.
Method

Method parameter description
GetAsFile is empty. If kind is file, you can use this method to obtain the file.
If kind is a string, you can use this method to obtain the string. The first parameter of the callback function is the string in the clipboard.
2.2.2 types attributes:

Common types values include text/plain, text/html, and Files.

Value description
Text/plain string.
Text/html with styles.
Files (such as data in the clipboard ).
<Input type = "text" id = "input">

Document. querySelector ("# input"). addEventListener ("paste", function (e ){
Var clipboardData = e. clipboardData | window. clipboardData,
I = 0,
Items,
Item,
Types;

If (clipboardData ){
Items = clipboardData. items;
If (! Items ){
Return;
        }
Item = items [0];

// Data type stored on the clipboard
Types = clipboardData. types | [];
For (I = 0; I <types. length; I ++ ){
If (types [I] === 'files '){
Item = items [I];
Break;
            }
        }

// Determine whether the image data is used
If (item & item. kind === 'file' & item. type. match (/^ image \/I )){
Alert ("This is an image .");
        }
    }
});
2.3 clipboardData object compatibility

ClipboardData object compatibility is as follows: http://caniuse.com/#search=Clipboard

Image_1au6rgnf5cn7etf1kt01cptvm9.png-40.2kB

3. Copy the text to the clipboard: document.exe cCommand ()

When the document object is converted to the design mode (select, set contentEditable, etc.), the document object provides an execCommand method, you can run the parameter command to manipulate the content of the editable area. Most commands of this method are operations on the selected area of the document (such as bold and italics). execCommand can be used to perform many operations on the active elements.

3.1 syntax:

Bool = document.exe cCommand (aCommandName, ashowdefaui UI, aValueArgument)
The parameters are as follows:

ACommandName: command name, such as cut, copy, and paste.
Ashowdefaui UI: no. The default value is false. Mozilla is not implemented.
AValueArgument: some commands require some additional parameter values (for example, insertimage needs to provide the image url ). The default value is null.
The method used to copy text to the clipboard is:

Document.exe cCommand ("copy", "false", null );
You can use document. queryCommandSupported ("copy"); or document. queryCommandEnabled ("copy"); method (the two methods have the same function) to check whether the browser supports the copy command.

Note that although Chrome supports command copying, both methods in Chorme return false values. It is also a method to check whether the document.exe cCommand method exists, but it is better to put the document.exe cCommand ("copy") call in the try-catch block.

// Select # text in the myEle label
Var myEle = document. getElementById ('# myEle '),
Range = document. createRange ();

Range. selectNode (myEle );
Window. getSelection (). addRange (range );

Try {
If(document.exe cCommand ){
// Copy the selected text to the clipboard
Document.exe cCommand ("copy", "false", null );
    }
} Catch {
// Commands cannot be copied.
}
Application example: display the image resources in the clipboard to the page

<Input type = "text" id = "input" placeholder = "paste the image into the text box">


// Display Image resources to the page
Function showImage (imageData ){
Var reader = new FileReader ();
Reader. onload = function (e ){
Var img = new Image ();
Img. src = e.tar get. result;
Document. body. appendChild (img );
};
// Read Image files
Reader. readAsDataURL (imageData );
}

Document. querySelector ("# input"). addEventListener ("paste", function (e ){
Var clipboardData = e. clipboardData,
Items,
Item,
Types;

If (clipboardData ){
Items = clipboardData. items;
If (! Items ){
Return;
        }
Item = items [0];
// Data type stored on the clipboard
Types = clipboardData. types | [];
For (var I = 0; I <types. length; I ++ ){
If (types [I] === "Files "){
Item = items [I];
Break;
            }
        }
// Determine whether the image data is used
If (item & item. kind === 'file' & item. type. match (/^ image \/I )){
Var blob = item. getAsFile ();
ShowImage (blob );
        }
    }
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.