IE and Firefox can support JavaScript to write content to the clipboard IE can easily support writing commands to the clipboard content. You can use execCommand() or window.clipboardData.
To use execCommand, you need to first select the content to be copied to the clipboard from the page, such as the following code:
var doc = obj.createTextRange();
doc.select();
doc.execCommand('copy');
The method of using window.clipboardData is as follows. The code also implements the function of writing to the clipboard under Firefox:
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 open the browser's security settings
}
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip)
return;
var trans = Components.classes["@mozilla.org/widget/transferable;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-string; 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 above code can write custom content to the clipboard in IE and Firefox, but Opera and WebKit kernel browsers have higher security requirements and do not support this way of directly operating the clipboard content with JavaScript. , we can only "save the country" through other scripting languages.
Opera, Safari, and Chrome use ActionScript to write content to the clipboard
The specific implementation can use flex or flash to realize the appearance of the original action button, replacing the original image or text button. Then when the button is clicked, execute the following ActionScript script:
//Get the content that needs to be written to the clipboard from the browser environment
var s:String = String(ExternalInterface.call ("getURL4Clipboard")); //getURL4Clipboard is the javascript method that returns the clipboard content on the page
//Set the clipboard content
System.setClipboard(s);
//Call the JavaScript functions that need to be continued after setting the clipboard content, such as prompting user information, etc.
ExternalInterface.call("copyURLCompleted"); //copyURLCompleted is the javascript method on the page, continue to execute the copy work