@erfffun/utils
Version:
Energi javascript utilities for web development
47 lines (40 loc) • 1.44 kB
JavaScript
// eslint-disable-next-line import/no-mutable-exports
let copyToClipboard;
// NOTE: navigator can not be used directly, because Gatsby would not be able to build (sees it as an undefined global variable).
// That is why wee need to wrap it with the next function
// eslint-disable-next-line func-names
(function (win) {
const { navigator } = win;
const doc = win.document;
const navClipboardSupport = navigator && navigator.clipboard; // check navigator first, otherwise Gatsby build will fai
/**
* Returns an Intl object for a specific locale.
* Creates maximum 1 instance per locale: uses internal cache.
*
* @function copyToClipboard
* @param {string} text - The text to be copied to the clipboard
* @return {Boolean} "true" when successfully copied the text to the clipboard; "false" otherwise
* @since 0.1.1
*/
copyToClipboard = async text => {
let result;
if (!navClipboardSupport) {
const body = doc.querySelector('body');
const area = doc.createElement('textarea');
body.appendChild(area);
area.value = text;
area.select();
try {
const successful = doc.execCommand('copy');
result = successful;
} catch (err) {
result = false;
}
body.removeChild(area);
return result;
}
result = await navigator.clipboard.writeText(text);
return result;
};
})(typeof global !== 'undefined' ? global : /* istanbul ignore next */ this);
export default copyToClipboard;