rushlink/assets/js/copyclipboard.js
2020-04-05 18:16:41 +02:00

40 lines
1.2 KiB
JavaScript

"use strict";
const COPY_TO_CLIPBOARD_STATUS_ID = "copyToClipboardStatus";
let copyToClipboardCtr = 0;
function copyToClipboardSuccess() {
let statusElem = document.getElementById(COPY_TO_CLIPBOARD_STATUS_ID);
statusElem.innerText = "URL copied!";
statusElem.classList.remove("fail");
statusElem.classList.add("success");
}
function copyToClipboardFail(cause) {
let statusElem = document.getElementById(COPY_TO_CLIPBOARD_STATUS_ID);
if (!cause) cause = "unknown error";
statusElem.innerText = "copy failed: " + cause;
statusElem.classList.remove("success");
statusElem.classList.add("fail");
}
function copyToClipboard(url) {
let copyEventIdx = ++copyToClipboardCtr;
if (!window.navigator.clipboard) {
let msg = "could not access clipboard";
if (window.location.protocol !== "https:") {
msg += ": website not using HTTPS"
}
copyToClipboardFail(msg);
return;
}
window.navigator.clipboard.writeText(url).then(() => {
if (copyToClipboardCtr !== copyEventIdx) return;
copyToClipboardSuccess();
}, () => {
if (copyToClipboardCtr !== copyEventIdx) return;
copyToClipboardFail();
});
}