Skip to content
This repository has been archived by the owner on Sep 2, 2024. It is now read-only.

Commit

Permalink
fix: copy to clipboard on non-https sites (#440)
Browse files Browse the repository at this point in the history
Co-authored-by: René Aaron <[email protected]>
  • Loading branch information
im-adithya and reneaaron authored Jun 13, 2024
1 parent 875ed2f commit 1dface9
Showing 1 changed file with 37 additions and 14 deletions.
51 changes: 37 additions & 14 deletions frontend/src/lib/clipboard.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,43 @@
import { toast } from "src/components/ui/use-toast";

export function copyToClipboard(content: string) {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(content);
} else {
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = content;
textArea.style.position = "absolute";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.select();
new Promise((res, rej) => {
document.execCommand("copy") ? res(content) : rej();
export async function copyToClipboard(content: string) {
const copyPromise = new Promise((resolve, reject) => {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(content).then(resolve).catch(reject);
} else {
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = content;
textArea.style.position = "absolute";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
selectElement(textArea);
if (document.execCommand("copy")) {
resolve(content);
} else {
reject();
}
textArea.remove();
}
});

try {
await copyPromise;
toast({ title: "Copied to clipboard." });
} catch (e) {
toast({
title: "Failed to copy to clipboard.",
variant: "destructive",
});
}
toast({ title: "Copied to clipboard." });
}

function selectElement(element: Element) {
const selection = window.getSelection();
if (selection) {
selection.removeAllRanges();
const range = document.createRange();
range.selectNode(element);
selection.addRange(range);
}
}

0 comments on commit 1dface9

Please sign in to comment.