如何使用Greasemonkey更改JavaScript变量?

Joe*_*Joe 2 javascript variables greasemonkey

这是我要修改的页面,我想绕过倒数计时器,如何编写脚本?有没有一种方法可以document.licenseform.btnSubmit.disabled使用Greasemonkey 将变量更改为yes?


<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>dsfsdf</title>
</head>
<body>
<form name="licenseform" method="post" action="">
<input name="btnSubmit" type="button" value="???">
</form>
<SCRIPT language=javascript type=text/javascript>
    <!--
                     var secs = 9;
                     var wait = secs * 1000;
                     document.licenseform.btnSubmit.value = "??? [" + secs + "]";
                     document.licenseform.btnSubmit.disabled = true;

                     for(i = 1; i <= secs; i++)
                     {
                           window.setTimeout("Update(" + i + ")", i * 1000);
                                   //??????????????("update("+i+")",i*1000)
                     }
                     window.setTimeout("Timer()", wait);


                     function Update(num)
                     {
                           if(num != secs)
                           {
                                 printnr = (wait / 1000) - num;
                                 document.licenseform.btnSubmit.value = "??? [" + printnr + "]";
                           }
                     }

                     function Timer()
                     {
                           document.licenseform.btnSubmit.disabled = false;
                           document.licenseform.btnSubmit.value = " ??? ";
                     }
                     -->
                     </SCRIPT>
    </td>
    <!--??????????-->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Jes*_*ett 5

替代使用的更安全的方法unsafeWindow是将代码注入文档中。您注入的代码将在与页面代码相同的上下文中运行,因此可以直接访问其中的所有变量。但是它将无法访问用户脚本代码其他部分中的变量或函数。

注入代码的另一个好处是,以这种方式编写的用户脚本可以在Chrome和Firefox中使用。Chrome完全不支持unsafeWindow

我最喜欢的注入代码的方法是编写一个函数,然后使用此可重复使用的代码来获取该函数的源代码:

// Inject function so that in will run in the same context as other
// scripts on the page.
function inject(func) {
    var source = func.toString();
    var script = document.createElement('script');
    // Put parenthesis after source so that it will be invoked.
    script.innerHTML = "("+ source +")()";
    document.body.appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)

要进行切换,btnSubmit您可以编写如下脚本:

function enableBtnSubmit() {
    document.licenseform.btnSubmit.disabled = false;
    document.licenseform.btnSubmit.value = " ??? ";
    // Or just invoke Timer()
}

function inject(func) {
    var source = func.toString();
    var script = document.createElement('script');
    script.innerHTML = "("+ source +")()";
    document.body.appendChild(script);
}

inject(enableBtnSubmit);
Run Code Online (Sandbox Code Playgroud)

请记住,当您以这种方式使用函数的序列化形式时,正常的关闭范围将不起作用。除非在函数内部定义变量,否则您注入的函数将无法访问脚本中的变量。