Fix copy logic
This commit is contained in:
+28
-7
@@ -12,15 +12,36 @@
|
||||
var target = document.getElementById(button.dataset.copy);
|
||||
if (!target) return;
|
||||
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 () {
|
||||
target.select();
|
||||
var done = function () {
|
||||
var was = button.textContent;
|
||||
button.textContent = 'Copied';
|
||||
setTimeout(function () { button.textContent = was; }, 1500);
|
||||
};
|
||||
if (navigator.clipboard) navigator.clipboard.writeText(target.value).then(done, function () {});
|
||||
else { document.execCommand('copy'); done(); }
|
||||
target.setSelectionRange(0, target.value.length); // iOS ignores select()
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(target.value).then(function () {
|
||||
say('Copied');
|
||||
}, copySelection);
|
||||
} else {
|
||||
copySelection();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user