IE and Firefox support JavaScript writing content to the clipboard
IE can easily support the command for writing clipboard content, execCommand () or window. clipboardData.
To use execCommand, you must first select the content to be copied to the clipboard from the page, as shown in the following code:
Copy codeThe Code is as follows:
Var doc = obj. createTextRange ();
Doc. select ();
Doc.exe cCommand ('copy ');
The method of using window. clipboardData is as follows. The Code also implements the function of writing the clipboard to Firefox:
Copy codeThe Code is as follows:
If (window. clipboardData) // IE
{
Window. clipboardData. clearData ();
Window. clipboardData. setData ("Text", txt );
}
Else if (window. netscape)
{
Try {netscape. security. PrivilegeManager. enablePrivilege ("UniversalXPConnect ");
}
Catch (e)
{
Alert ("please visit 'about: config' and set signed. applets. codebase_principal_support as 'true '");
// Prompt the user to set the security of the open browser
}
Var clip = Components. classes ["@ mozilla.org/widget/clipboard1_1"]. createInstance (Components. interfaces. nsIClipboard );
If (! Clip)
Return;
Var trans = Components. classes ["@ mozilla.org/widget/transferable1_1"]. createInstance (Components. interfaces. nsITransferable );
If (! Trans)
Return;
Trans. addDataFlavor ('text/unicode ');
Var str = new Object ();
Var len = new Object ();
Var str = Components. classes ["@ mozilla.org/supports-string1_1"]. createInstance (Components. interfaces. nsISupportsString );
Var copytext = txt;
Str. data = copytext;
Trans. setTransferData ("text/unicode", str, copytext. length * 2 );
Var clipid = Components. interfaces. nsIClipboard;
If (! Clip)
Return;
Clip. setData (trans, null, clipid. kGlobalClipboard );
}
The preceding code can write custom content to the clipboard in IE and Firefox. However, the opera and webkit kernel browsers have higher security requirements and do not support direct operations on the clipboard using javascript, only other scripting languages can be used to "save the nation.
Opera, Safari, and Chrome use ActionScript to write content to the clipboard
For specific implementation, you can use flex or flash to implement the appearance of the original action button, replace the original image or text button, and then execute the following script when you click the button:
// Obtain the content to be written to the clipboard from the browser Environment
Var s: String = String (ExternalInterface. call ("getURL4Clipboard"); // getURL4Clipboard is the javascript method for returning the clipboard content on the page.
// Set the clipboard content
System. setClipboard (s );
// Call the JavaScript function that needs to be continued after the clipboard content is set, such as prompting user information.
ExternalInterface. call ("copyURLCompleted"); // copyURLCompleted is the javascript method on the page. Continue the copy operation.