copyUrl.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. function CopyToClipboard(input) {
  2. var textToClipboard = input;
  3. var success = true;
  4. if (window.clipboardData) { // Internet Explorer
  5. window.clipboardData.setData("Text", textToClipboard);
  6. } else {
  7. // create a temporary element for the execCommand method
  8. var forExecElement = CreateElementForExecCommand(textToClipboard);
  9. /* Select the contents of the element
  10. (the execCommand for 'copy' method works on the selection) */
  11. SelectContent(forExecElement);
  12. var supported = true;
  13. // UniversalXPConnect privilege is required for clipboard access in Firefox
  14. try {
  15. if (window.netscape && netscape.security) {
  16. netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  17. }
  18. // Copy the selected content to the clipboard
  19. // Works in Firefox and in Safari before version 5
  20. success = document.execCommand("copy", false, null);
  21. } catch (e) {
  22. success = false;
  23. }
  24. // remove the temporary element
  25. document.body.removeChild(forExecElement);
  26. }
  27. if (success) {
  28. alert("复制成功!");
  29. } else {
  30. alert("复制失败,你要复制的内容为:"+textToClipboard);
  31. }
  32. }
  33. function CreateElementForExecCommand(textToClipboard) {
  34. var forExecElement = document.createElement("div");
  35. // place outside the visible area
  36. forExecElement.style.position = "absolute";
  37. forExecElement.style.left = "-10000px";
  38. forExecElement.style.top = "-10000px";
  39. // write the necessary text into the element and append to the document
  40. forExecElement.textContent = textToClipboard;
  41. document.body.appendChild(forExecElement);
  42. // the contentEditable mode is necessary for the execCommand method in Firefox
  43. forExecElement.contentEditable = true;
  44. return forExecElement;
  45. }
  46. function SelectContent(element) {
  47. // first create a range
  48. var rangeToSelect = document.createRange();
  49. rangeToSelect.selectNodeContents(element);
  50. // select the contents
  51. var selection = window.getSelection();
  52. selection.removeAllRanges();
  53. selection.addRange(rangeToSelect);
  54. }