问题
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() );
});
}
回答1:
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:
That error message (if it hasn't been edited) suggests that the script did not activate
GM_getValueproperly. You must set appropriate @grant values to use GM_ functions. EG:// @grant GM_getValue // @grant GM_setValueThe 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.
回答2:
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);
});
来源:https://stackoverflow.com/questions/16014987/gm-getvalue-undefined-error