js初学者代码写的不好,勉强能用,如果纯用油猴的话还能用更简洁的GM_setClipboard,我写的这个如果站长愿意可以直接加载到页面上。
油猴添加自定义脚本,代码如下
// ==UserScript==
// @name AHK网站复制代码
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 给autoahk网站页面增加复制代码按钮
// @author usnake
// @match https://www.autoahk.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=autoahk.com
// @grant none
// ==/UserScript==
(function(){
let prettyprinted = document.querySelectorAll('.prettyprinted');
for(let i=0;i<prettyprinted.length;i++){
prettyprinted[i].insertAdjacentHTML('beforebegin', `<div style="position:relative;"><div class="copydiv" style="
color: #9999aa;
background-color:#3a404a;
position: absolute;
top: 14px;
right: 21px;
font-size: 12px;
line-height: 26px;
padding: 0 8px;
border-radius: 2px;
cursor: pointer;
z-index: 5;
" onclick="copy_code(this)">复制全部</div></div>`);
}
copy_code = function(e){
let code_str = e.parentElement.nextElementSibling.innerText;
copyTextToClipboard(code_str);
}
function fallbackCopyTextToClipboard() {
// 1.创建一个可选中元素
let textArea = document.createElement("textarea");
textArea.value = window.location.href;
// 2.使用定位,阻止页面滚动
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
// 3.移除元素
document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
navigator.clipboard.writeText(text).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}
})();
使用油猴脚本进行了测试,非常nice!感谢分享!