franca-theme-blog/static/js/copy.js

58 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-07-22 13:18:15 +00:00
function addCopyButtons(clipboard) {
document.querySelectorAll('pre').forEach(function (preElement) {
// Создание кнопки
var button = document.createElement('button');
button.className = 'copy-code-button';
button.type = 'button';
var lang = document.documentElement.lang;
var button_text = "Copy";
var button_text_copied = "Copied!";
if (lang == "ru") {
button_text = "Копировать";
button_text_copied = "Скопировано!";
}
button.innerText = button_text;
// Добавление слушателя к кнопке
button.addEventListener('click', function () {
clipboard.writeText(preElement.innerText).then(function () {
/* Chrome doesn't seem to blur automatically,
leaving the button in a focused state. */
button.blur();
if (lang == "ru-RU") {
button_text = "Копировать";
button_text_copied = "Скопировано!";
}
button.innerText = button_text_copied;
setTimeout(function () {
button.innerText = button_text;
}, 1000);
}, function (error) {
button.innerText = 'Error';
});
});
// wrapper.appendChild(preElement);
var preParent = preElement.parentNode;
2023-07-23 12:53:48 +00:00
if (preParent.classList.contains('codehilite') && preElement.children[0].dataset.lang != 'plaintext') {
2023-07-22 13:18:15 +00:00
preParent.parentNode.insertBefore(button, preParent);
}
});
}
if (navigator && navigator.clipboard) {
addCopyButtons(navigator.clipboard);
} else {
var script = document.createElement('script');
script.src = '/js/clipboard-polyfill.promise.js';
script.onload = function() {
addCopyButtons(clipboard);
};
document.body.appendChild(script);
}