GM_getValue undefined error

∥☆過路亽.° 提交于 2019-12-25 16:51:44

问题


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:

  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.




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!