Skip to content

Commit

Permalink
fix: support code copy in firefox & safari, close #39
Browse files Browse the repository at this point in the history
  • Loading branch information
tomowang committed May 14, 2024
1 parent 88ad924 commit 8e78440
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion assets/js/code-copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,25 @@
if (highlightDiv.querySelector("table")) { // code with line number
codeToCopy = highlightDiv.querySelector("td:last-child code").textContent;
}
let permissionGranted = true;
try {
var result = await navigator.permissions.query({ name: "clipboard-write" });
if (result.state == "granted" || result.state == "prompt") {
if (result.state != "granted" && result.state != "prompt") {
permissionGranted = false;
}
} catch (_) {
// The clipboard-write permission name is not supported in Firefox, only Chromium browsers.
// default to true in case of error for firefox
}

try {
if (permissionGranted) {
await navigator.clipboard.writeText(codeToCopy);
} else {
copyCodeBlockExecCommand(codeToCopy, highlightDiv);
}
} catch (_) {
copyCodeBlockExecCommand(codeToCopy, highlightDiv);
} finally {
/* Chrome doesn't seem to blur automatically,
leaving the button in a focused state. */
Expand All @@ -38,4 +52,21 @@
}, 2000);
}
}

function copyCodeBlockExecCommand(codeToCopy, highlightDiv) {
const textArea = document.createElement("textArea");
textArea.contentEditable = "true";
textArea.readOnly = "false";
textArea.className = "copyable-text-area";
textArea.value = codeToCopy;
highlightDiv.insertBefore(textArea, highlightDiv.firstChild);
const range = document.createRange();
range.selectNodeContents(textArea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textArea.setSelectionRange(0, 999999);
document.execCommand("copy");
highlightDiv.removeChild(textArea);
}
})();

0 comments on commit 8e78440

Please sign in to comment.