jQuery simply implements the method of clicking a text box to copy content to the clipboard

  • 2021-07-06 10:09:18
  • OfStack

This article illustrates how jQuery simply clicks on a text box to copy content to the clipboard. Share it for your reference, as follows:


// Click the text box to copy its contents to the method on the clipboard 
function copyToClipboard(txt) {
  if (window.clipboardData) {
    window.clipboardData.clearData();
    window.clipboardData.setData("Text", txt);
    alert(" It has been successfully copied to the clipboard! ");
  } else if (navigator.userAgent.indexOf("Opera") != -1) {
    window.location = txt;
  } else if (window.netscape) {
    try {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
      alert(" Rejected by browser! \n Please enter in the browser address bar 'about:config' And enter \n Then the 'signed.applets.codebase_principal_support' Set to 'true'");
    }
    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 false;
    clip.setData(trans, null, clipid.kGlobalClipboard);
    alert(" It has been successfully copied to the clipboard! ");
  }
}
// Click the text box to copy its contents to the clipboard 
function setCopyLink() {
  $("#txt_CopyLink").val(document.URL)
  .focus(function () {
    $(this).css({ "background-color": "#ddd" }).select();
    copyToClipboard($("#txt_CopyLink").val());
  }).blur(function () {
    $(this).css({ "background-color": "#fff" });
  });
}

For more readers interested in jQuery related content, please check the topics of this site: "Summary of Usage and Skills of Common Events of jQuery", "Summary of Operation Skills of jQuery form", "Summary of Common Plug-ins and Usage of jQuery", "Summary of Data Skills of jQuery Operation of json", "Summary of Extension Skills of jQuery", "Summary of Operation Skills of jQuery Table (table)", "Summary of Common Classic Special Effects of jQuery", "Summary of Animation and Special Effects Usage of jQuery" and "Summary of Usage of jquery Selector"

I hope this article is helpful to everyone's jQuery programming.


Related articles: