Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GM_getValue is not defined (in injected code)?

I saw GM_getValue undefined error, however I did grant GM_getValue and GM_setValue and defined a default value.

Example code:

// ==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);

If you right click on the "add answer" textarea on SO after installing the above example, FF says GM_getValue is undefined in the console. Why is this?

How do I get GM functions to work?

like image 947
gandalf3 Avatar asked Jul 08 '14 22:07

gandalf3


1 Answers

That script is trying to run GM_getValue() from within the target-page scope (injected code); this is not allowed.
If the code really must be injected, use the techniques from:
How to use GM_xmlhttpRequest in Injected Code?
or
How to call Greasemonkey's GM_ functions from code that must run in the target page scope?
to utilize GM_ functions.

However, that script is using an obsolete and dangerous way to add jQuery. Don't do things like that. Worst-case, use this optimized, cross-platform method (second example). But, since you are on Greasemonkey (or Tampermonkey) that script can me made: much simpler, more secure, faster, and more efficient like so:

// ==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) );
});
like image 137
Brock Adams Avatar answered Nov 11 '22 08:11

Brock Adams