GM_getValue未定义(在注入的代码中)?

gan*_*lf3 6 greasemonkey code-injection

我看到GM_getValue未定义的错误,但我没有补助GM_getValueGM_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)

如果在安装上面的示例后右键单击SO上的"添加答案"textarea,FF会GM_getValue is undefined在控制台中说明.为什么是这样?

如何让GM功能起作用?

Bro*_*ams 9

该脚本试图GM_getValue()从目标页面范围内运行(注入代码); 这是不允许的.
如果必须注入代码,请使用以下技术:
如何在注入代码中使用GM_xmlhttpRequest?
或者
如何从必须在目标页面范围内运行的代码调用Greasemonkey的GM_函数?
利用GM_功能.

但是,该脚本使用了一种过时且危险的方式来添加jQuery.不要做那样的事情.最坏情况,使用这种优化的跨平台方法(第二个例子).但是,既然你使用的是Greasemonkey(或Tampermonkey),我可以编写脚本:更简单,更安全,更快速,更高效,如下所示:

// ==UserScript==
// @name    SO_test
// @include https://stackoverflow.com/*
// @version 1
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant   GM_getValue
// @grant   GM_setValue
// ==/UserScript==

$("#wmd-input").on ("contextmenu", function (e) {
    e.preventDefault ();

    //-- Important: note the comma and the correct case for `true`.
    console.log ("GM_getValue: ", GM_getValue ("extra_markdown", true) );
});
Run Code Online (Sandbox Code Playgroud)