我使用Windows10家庭版和最新的Firefox和Greasemonkey。
我在 livedns.co.il 创建了一个帐户,这是一个以色列域名注册。然后我登录了。
登录到个人概述区域后,我尝试通过以下代码将自己移动到域管理区域:
window.location.href = "https://domains.livedns.co.il/DomainsList.aspx";
它在控制台中工作,但不能从油猴脚本中工作。
我想我可能需要在脚本中加入setTimeout()
:
setTimeout(()=>{
window.location.href = "https://domains.livedns.co.il/DomainsList.aspx";
}, 1000);
但此代码也仅在控制台中有效。
重现步骤
创建帐户并登录后,这是我使用的原始模式:
// ==UserScript==
// @name livednsAutoLogin
// @include https://domains.livedns.co.il/Default.aspx
// ==/UserScript==
console.log(window.location.href); // This fails in Greasemonkey if the code below exists; If I'll delete all code below, it will succeed in Greasemonkey;
document.querySelector("#ctl00_TopLoginBox1_txtUname").value = "myUsername";
document.querySelector("#ctl00_TopLoginBox1_txtPassword").value = "myPassword";
document.querySelector("#ctl00_TopLoginBox1_btnLogin > .FltRt").click();
setTimeout(()=>{
window.location.href = "https://domains.livedns.co.il/DomainsList.aspx";
}, 250);
只需更改用户名和密码,然后进行测试。
我的问题
是什么让普通的JavaScript代码在控制台中工作,而不是从(greasemonkey)脚本中工作?特别是,为什么更改文档位置的 href 仅在控制台中有效,而在 Greasemonkey 脚本中无效?
我不知道在这种情况下如何调试,因为我在运行脚本时在控制台中看不到错误。
从错误的 url 运行代码时我遇到了一个逻辑错误(我应该确保我https://domains.livedns.co.il/Main.aspx
成功运行代码。我通过使用 if-then 条件解决了这个问题(我会发现我是否使用这种方式有任何重大的安全威胁)。
请注意我如何更改@include
并更丰富地使用 URL。
// ==UserScript==
// @name livednsAutoLogin
// @include *livedns.co.il/*
// ==/UserScript==
if ( document.location.href == "https://domains.livedns.co.il/" ) {
document.querySelector("#ctl00_TopLoginBox1_txtUname").value = "myEmail";
document.querySelector("#ctl00_TopLoginBox1_txtPassword").value = "myPassword";
document.querySelector("#ctl00_TopLoginBox1_btnLogin > .FltRt").click();
}
if ( document.location.href == "https://domains.livedns.co.il/Main.aspx" ) {
console.log(window.location.href);
document.location.href = "https://domains.livedns.co.il/DomainsList.aspx"
}