插件描述
通过该插件,我们可以在浏览器上管理和运行自定义脚本,例如:为站点添加功能、修改网页内容、自定义某些行为。
我们曾经使用它:
1)抓取过美剧天堂中《老友记》下载地址;
2)创建复制快捷键,按下快捷键,在剪贴板中创建特定格式文本;
相关链接
常见问题汇总(FAQ)
如何引入第三方代码库(JS)?
javascript - Trying to load jquery into tampermonkey script - Stack Overflow
Tampermonkey • Documentation / require
只需要在头部使用 @require 标签(引入多个文件则使用多次):
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @require https://cdn.bootcdn.net/ajax/libs/notify/0.4.2/notify.min.js
需求:复制特定格式的文本
Adding a custom keyboard shortcut using userscript to Chrome with Tampermonkey
Include all pages in tampermonkey(userscript)
Capturing ctrl+z key combination in javascript
How do I copy to the clipboard in JavaScript?
How to get current html page title with javascript
keyboard events - javascript alt key - Stack Overflow
JavaScript String fromCharCode() Method
Get the current URL with JavaScript? - Stack Overflow
如何页面显示消息提示,并自动消失:Auto-hide Notify
JavaScript try/catch/finally Statement
问题描述
我们需要在 Wiki 中添加参考文献的链接,但是我们希望通过快捷键直接复制出 Wiki 语法格式的文本。
解决方案
因此,我们编写如下代码,1)用于复制操作,2)并在复制成功后进行提示:
// ==UserScript==
// @name ZIM@COPY-REFERENCE
// @namespace https://k4nz.com/
// @version 0.2.1
// @description try to take over the world!
// @author k4nzmailsup@163.com
// @match *://*/*
// @grant none
// @require http://libs.baidu.com/jquery/2.0.0/jquery.min.js
// @require https://cdn.bootcdn.net/ajax/libs/notify/0.4.2/notify.min.js
// ==/UserScript==
(function() {
'use strict';
function copyTextToClipboard(text) {
// 如果支持 navigator.clipboard 时使用
if (navigator.clipboard) {
navigator.clipboard.writeText(text);
return true; // 我们不理会异步,假装成功
}
// 当浏览器不支持 navigator.clipboard 时使用
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
return document.execCommand('copy');
} catch (err) {
return false;
} finally {
document.body.removeChild(textArea);
}
}
document.addEventListener('keydown', function(e) {
if (e.altKey && e.shiftKey && String.fromCharCode(e.keyCode).toUpperCase() == "W") {
// 创建要写入剪贴板的文本
var pageTitle = document.title
var pageLink = window.location.href
var wikiReference = "[[" + pageLink + " |" + pageTitle + "]]"
console.log("Wiki Reference: " + wikiReference);
// 写入剪贴板
var copySuccess = copyTextToClipboard(wikiReference);
jQuery.notify("Wiki Reference Copy Result: " + copySuccess, copySuccess ? "success" : "error");
}
}, false);
})();