Fix copy logic
This commit is contained in:
+28
-7
@@ -12,15 +12,36 @@
|
|||||||
var target = document.getElementById(button.dataset.copy);
|
var target = document.getElementById(button.dataset.copy);
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
button.hidden = false;
|
button.hidden = false;
|
||||||
|
|
||||||
|
var label = button.textContent, timer;
|
||||||
|
function say(word) {
|
||||||
|
button.textContent = word;
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(function () { button.textContent = label; }, 1500);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copying the selection needs neither a permission nor a secure context,
|
||||||
|
// so it answers for both of the ways the clipboard API can let us down:
|
||||||
|
// missing entirely (this service is reached over plain HTTP as well as
|
||||||
|
// HTTPS, and the API exists only on the secure side) or present and
|
||||||
|
// refusing (an unfocused document, a permissions policy). If even that
|
||||||
|
// fails, the text is selected either way, so say what to press.
|
||||||
|
function copySelection() {
|
||||||
|
var ok = false;
|
||||||
|
try { ok = document.execCommand('copy'); } catch (e) { /* ok stays false */ }
|
||||||
|
say(ok ? 'Copied' : 'Press Ctrl-C');
|
||||||
|
}
|
||||||
|
|
||||||
button.addEventListener('click', function () {
|
button.addEventListener('click', function () {
|
||||||
target.select();
|
target.select();
|
||||||
var done = function () {
|
target.setSelectionRange(0, target.value.length); // iOS ignores select()
|
||||||
var was = button.textContent;
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||||
button.textContent = 'Copied';
|
navigator.clipboard.writeText(target.value).then(function () {
|
||||||
setTimeout(function () { button.textContent = was; }, 1500);
|
say('Copied');
|
||||||
};
|
}, copySelection);
|
||||||
if (navigator.clipboard) navigator.clipboard.writeText(target.value).then(done, function () {});
|
} else {
|
||||||
else { document.execCommand('copy'); done(); }
|
copySelection();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user