UNPKG

copy-text-to-clipboard-async

Version:
80 lines (76 loc) 3 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); /** Copy text to the clipboard. Must be called in response to a user gesture event, like `click` or `keyup`. @param text - The text to copy to clipboard. @param options - Copy options. @returns Promise that resolves if the text was successfully copied or rejects if the operation failed. @example ``` import copy from 'copy-text-to-clipboard-async'; button.addEventListener('click', () => { copy('🦄🌈') .then(() => console.log('🎉')) .catch(() => console.error('😢')); }); ``` */ const copyTextToClipboard = (input, { target = document.body } = {}) => __awaiter(void 0, void 0, void 0, function* () { if (navigator.clipboard) { try { yield navigator.clipboard.writeText(input); return Promise.resolve(); } catch (_a) { } } const element = document.createElement('textarea'); const previouslyFocusedElement = document.activeElement; element.value = input; // Prevent keyboard from showing on mobile element.setAttribute('readonly', ''); // @ts-ignore element.style.contain = 'strict'; element.style.position = 'absolute'; element.style.left = '-9999px'; element.style.fontSize = '12pt'; // Prevent zooming on iOS const selection = document.getSelection(); let originalRange = false; if (selection.rangeCount > 0) { originalRange = selection.getRangeAt(0); } target.append(element); element.select(); // Explicit selection workaround for iOS element.selectionStart = 0; element.selectionEnd = input.length; let isSuccess = false; try { isSuccess = document.execCommand('copy'); } catch (_b) { } element.remove(); if (originalRange) { selection.removeAllRanges(); selection.addRange(originalRange); } // Get the focus back on the previously focused element, if any if (previouslyFocusedElement) { previouslyFocusedElement.focus(); } return isSuccess ? Promise.resolve() : Promise.reject(); }); exports.default = copyTextToClipboard; module.exports = copyTextToClipboard; module.exports.default = copyTextToClipboard; //# sourceMappingURL=index.js.map