Skip to content

Instantly share code, notes, and snippets.

@max10rogerio
Last active November 22, 2023 00:13
Show Gist options
  • Save max10rogerio/26573ccf702fe281c40bfc15b4219b87 to your computer and use it in GitHub Desktop.
Save max10rogerio/26573ccf702fe281c40bfc15b4219b87 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 (error) {
console.log(error.toString());
}
};
@SampathEB
Copy link

fgfgfg

@SampathEB
Copy link

clipboard

@ninjasero
Copy link

type of error is unknown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment