Skip to content

Instantly share code, notes, and snippets.

@nblackburn
Created May 2, 2020 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nblackburn/852cfefc01f7525bf097656aa61ce8da to your computer and use it in GitHub Desktop.
Save nblackburn/852cfefc01f7525bf097656aa61ce8da to your computer and use it in GitHub Desktop.
Clipboard
const PERMISSION_WRITE = 'clipboard-write';
const canUseAsyncAPI = () => {
return (
navigator.clipboard &&
navigator.clipboard.writeText &&
navigator.permissions &&
navigator.permissions.request
);
};
const legacyCopy = text => {
return new Promise((resolve, reject) => {
let focusTarget = null;
let element = document.createElement('textarea');
// Capture the original focus.
const focusHandler = event => {
focusTarget = event.originalTarget;
};
element.value = text;
element.addEventListener('focus', focusHandler);
document.body.appendChild(element);
element.focus();
element.select();
try {
document.execCommand('copy');
element.removeEventListener('focus', focusHandler);
// Restore the original focus.
if (focusTarget !== undefined) {
focusTarget.focus();
}
resolve();
} catch (e) {
reject();
}
document.body.removeChild(element);
});
};
const asyncCopy = text => {
return new Promise((resolve, reject) => {
navigator.permissions
.request({ name: PERMISSION_WRITE })
.then(() => {
navigator.clipboard
.writeText(text)
.then(resolve)
.catch(reject);
})
.catch(reject);
});
};
const copy = text => {
return canUseAsyncAPI() ? asyncCopy(text) : legacyCopy(text);
};
module.exports = copy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment