fix: clipboard copy in safari (#3261)

This commit is contained in:
kloon15 2024-06-08 21:56:48 +02:00 committed by GitHub
parent a8388689f3
commit 1fccc5d649
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 9 additions and 9 deletions

View File

@ -1,9 +1,11 @@
// Based on code provided by Amir Fo // Based on code by the following links:
// https://stackoverflow.com/a/74528564 // https://stackoverflow.com/a/74528564
// https://web.dev/articles/async-clipboard
export function copy(text: string) { export function copy(text: string) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
if ( if (
typeof navigator !== "undefined" && // Clipboard API requires secure context
window.isSecureContext &&
typeof navigator.clipboard !== "undefined" && typeof navigator.clipboard !== "undefined" &&
// @ts-ignore // @ts-ignore
navigator.permissions !== "undefined" navigator.permissions !== "undefined"
@ -13,10 +15,8 @@ export function copy(text: string) {
.query({ name: "clipboard-write" }) .query({ name: "clipboard-write" })
.then((permission) => { .then((permission) => {
if (permission.state === "granted" || permission.state === "prompt") { if (permission.state === "granted" || permission.state === "prompt") {
const type = "text/plain"; // simple writeText should work for all modern browsers
const blob = new Blob([text], { type }); navigator.clipboard.writeText(text).then(resolve).catch(reject);
const data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data).then(resolve).catch(reject);
} else { } else {
reject(new Error("Permission not granted!")); reject(new Error("Permission not granted!"));
} }
@ -66,7 +66,7 @@ const styles = {
border: "none", border: "none",
outline: "none", outline: "none",
boxShadow: "none", boxShadow: "none",
background: "transparent" background: "transparent",
}; };
const createTemporaryTextarea = (text: string) => { const createTemporaryTextarea = (text: string) => {