user2118839
user2118839

Reputation: 63

GM_getValue undefined error

In my greasemonkey script I want to check if the GM Value : Username and Password isset but when i try the following code it gives me back the error :

TypeError: GM_getValue(...) is undefined    
...f (GM_getValue ("username").length == 0 + GM_getValue ("password").length == 0 )

Code:

if (GM_getValue ("username").length == 0 + GM_getValue ("password").length == 0 ){
var username = $('input[name=username]');
var password = $('input[name=password]');

//Username en Password in Firefox zetten met GM_setValue
$(".button").click(function(){

GM_setValue ("username", username.val() );
GM_setValue ("password", password.val() );

});
}

Upvotes: 0

Views: 4950

Answers (2)

Brock Adams
Brock Adams

Reputation: 93473

GM_getValue does not return an array and does not have a length property.
That function returns undefined if the value was not set. The proper way to do the check you are attempting is:

var uName = GM_getValue ("username", "");
var pWord = GM_getValue ("password", "");

if ( ! uName   &&  ! pWord) {
    uName = $('input[name=username]').val();
    pWord = $('input[name=password]').val();
}


However, two additional things to know/consider:

  1. That error message (if it hasn't been edited) suggests that the script did not activate GM_getValue properly. You must set appropriate @grant values to use GM_ functions. EG:

    // @grant    GM_getValue
    // @grant    GM_setValue
    
  2. The approach you are starting:

    • Has errors -- hence the need for this question.
    • Has usability problems which you will discover.
    • Doesn't have convenience or security features.

So, don't reinvent the wheel without a darn good reason. There are already proven, more-secure, full-featured frameworks for this kind of thing. Here's a good one.

Upvotes: 7

Hellion
Hellion

Reputation: 1740

First, I'm not sure if you can check the length of a function's return value directly like that. Second, you definitely shouldn't be adding booleans like that either, you need the boolean-AND operator && instead of +. Try something like this:

var username = GM_getValue("username");
var password = GM_getValue("password");
if ((username.length == 0) && (password.length == 0)) {
    username = $('input[name=username]').val();
    password = $('input[name=password]').val();
}
$(".button").click(function(){
    GM_setValue ("username", username);
    GM_setValue ("password", password);
});

Upvotes: 0

Related Questions