Skip to content

Instantly share code, notes, and snippets.

@max10rogerio
Last active Jul 13, 2020
Embed
What would you like to do?
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 (error) {
console.log(error.toString());
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment