我没有"安装"用户脚本,而是在网上找到了许多手动添加它的教程.所有人都告诉我要做同样的步骤:
我这样做了 - 但我的演示脚本没有做任何事情:
// ==UserScript==
// @name Test
// @description Test
// @include http://example.com/*
// @version 1.0
// ==/UserScript==
alert(0);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我看到GM_getValue未定义的错误,但我没有补助GM_getValue和GM_setValue与定义的默认值.
示例代码:
// ==UserScript==
// @name SO_test
// @include https://stackoverflow.com/*
// @version 1
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
// Get jQuery thanks to this SO post:
// https://stackoverflow.com/a/3550261/2730823
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
function main() {
$("#wmd-input").on("contextmenu", function(e) {
e.preventDefault();
console.log("GM_getValue: " + GM_getValue("extra_markdown", True));
});
}
addJQuery(main); …Run Code Online (Sandbox Code Playgroud) 假设我正在使用以下网页:
<html>
<body>
<span id="click">click me</span>
<script>
var hello = function() {
alert('hello');
}
document.getElementById('click').addEventListener('click', function(e) {
hello();
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的Greasemonkey脚本是:
// ==UserScript==
// @name My Script
// @include http://example.com/hello.html
// @version 1
// @grant none
// ==/UserScript==
window.hello = function() {
alert('goodbye');
}
Run Code Online (Sandbox Code Playgroud)
禁用Greasemonkey脚本后,单击#click页面上的元素将显示"hello"警报.启用脚本后,单击该元素将显示"再见"警报.
很简单.在hello从网页的功能正在由Greasemonkey的脚本功能所取代.
现在让我们说我想使用Greasemonkey API.当我将@grant值设置为除'none'之外的有效值(例如// @grant GM_setClipboard)[导致Greasemonkey将脚本作为"内容脚本"运行时,而不是像'none'那样在页面的范围内运行),Greasemonkey脚本无法工作.
window.hello 不再定位页面上的正确对象.
更换window.hello用unsafeWindow.hello看起来像它的工作,而是下面的错误是在JS控制台抛出:
错误:拒绝访问对象的权限
如何在@grant GM_setClipboard设置目标并替换hello页面上的原始函数时重写Greasemonkey脚本?
系统信息: