clipboard.lib.ts 621 B

12345678910111213141516171819202122
  1. export function useClipboard() {
  2. function copy(text: string) {
  3. if (navigator.clipboard && window.isSecureContext) {
  4. return navigator.clipboard.writeText(text)
  5. } else {
  6. const textArea = document.createElement("textarea");
  7. textArea.value = text
  8. textArea.style.position = "absolute";
  9. textArea.style.opacity = '0';
  10. document.body.appendChild(textArea);
  11. textArea.select();
  12. return new Promise((resolve, reject) => {
  13. document.execCommand("copy") ? resolve('') : reject(new Error("出错了"));
  14. textArea.remove()
  15. })
  16. }
  17. }
  18. return { copy }
  19. }