javascript copy text to clipborad


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function copyToClipboard(txt) {
  2. if(window.clipboardData) {
  3. window.clipboardData.clearData();
  4. window.clipboardData.setData("Text", txt);
  5. } else if(navigator.userAgent.indexOf("Opera") != -1) {
  6. window.location = txt;
  7. } else if (window.netscape) {
  8. try {
  9. netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  10. } catch (e) {
  11. alert("被瀏覽器拒絕!\n請在瀏覽器地址欄輸入'about:config'並回車\n然後將'signed.applets.codebase_principal_support'設置為'true'");
  12. }
  13. var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
  14. if (!clip)
  15. return;
  16. var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
  17. if (!trans)
  18. return;
  19. trans.addDataFlavor('text/unicode');
  20. var str = new Object();
  21. var len = new Object();
  22. var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  23. var copytext = txt;
  24. str.data = copytext;
  25. trans.setTransferData("text/unicode",str,copytext.length*2);
  26. var clipid = Components.interfaces.nsIClipboard;
  27. if (!clip)
  28. return false;
  29. clip.setData(trans,null,clipid.kGlobalClipboard);
  30. }
  31. alert('已經複製');
  32. }
  33. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.