-
-
Save johnfmorton/a6ff03f6e7fc54a484ba02cd5f9d3767 to your computer and use it in GitHub Desktop.
Example Copy to Clipboard with Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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