Last active
November 22, 2023 00:13
-
-
Save max10rogerio/26573ccf702fe281c40bfc15b4219b87 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 (error) { | |
console.log(error.toString()); | |
} | |
}; |
clipboard
type of error
is unknown
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fgfgfg