Skip to content

Commit a04aecf

Browse files
committed
解决代码块复制只能在https安全上下文中复制问题
1 parent 92c8cae commit a04aecf

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

resources/views/documents/articles/show.blade.php

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -396,13 +396,19 @@ function addCopyButtons() {
396396
button.textContent = '复制';
397397
398398
button.addEventListener('click', function() {
399-
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
400-
button.textContent = '已复制!';
399+
var textArea = document.createElement('textarea');
400+
textArea.value = codeBlock.textContent;
401+
document.body.appendChild(textArea);
402+
textArea.select();
403+
try {
404+
var successful = document.execCommand('copy');
405+
button.textContent = successful ? '复制完成!' : '复制失败';
401406
setTimeout(() => { button.textContent = '复制'; }, 2000);
402-
}, function(err) {
407+
} catch (err) {
403408
button.textContent = '复制失败';
404409
console.error('Error copying text: ', err);
405-
});
410+
}
411+
document.body.removeChild(textArea);
406412
});
407413
408414
if (!pre.parentNode.classList.contains('code-block')) {
@@ -413,7 +419,8 @@ function addCopyButtons() {
413419
}
414420
pre.appendChild(button);
415421
});
416-
}
422+
}
423+
417424
418425
419426

0 commit comments

Comments
 (0)