Skip to content

Instantly share code, notes, and snippets.

@johnfmorton
Forked from max10rogerio/clipboard.ts
Created December 28, 2022 19:15
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 johnfmorton/a6ff03f6e7fc54a484ba02cd5f9d3767 to your computer and use it in GitHub Desktop.
Save johnfmorton/a6ff03f6e7fc54a484ba02cd5f9d3767 to your computer and use it in GitHub Desktop.
Example Copy to Clipboard with Typescript
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard
/**
* Interface CopyToClipboard params
*/
interface ICopyToClipboard {
/** HTML reference identifier ```<div id="foo"></div>``` */
target?: string;
/** String value */
value?: string;
/** (Optional) message to display in snackbar on success */
message?: string;
}
export const copyToClipboard = async ({ target, message, value }: ICopyToClipboard) => {
try {
let copyValue = "";
if (!navigator.clipboard) {
throw new Error("Browser don't have support for native clipboard.");
}
if (target) {
const node = document.querySelector(target);
if (!node || !node.textContent) {
throw new Error("Element not found");
}
value = node.textContent;
}
if (value) {
copyValue = value;
}
await navigator.clipboard.writeText(copyValue);
console.log(message ?? "Copied!!!");
} catch (err) {
if (err instanceof Error) {
// ✅ TypeScript knows err is Error
console.error(err.message);
} else {
console.error('Unexpected error', err);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment