【问题标题】:Vanilla JavaScript code works in console but not from a (greasemonkey) scriptVanilla JavaScript 代码在控制台中工作,但不能来自(greasemonkey)脚本
【发布时间】:2018-04-10 19:31:42
【问题描述】:

我使用 Windows10 home 和最新的 Firefox 和 Greasemonkey。

我在livedns.co.il 中创建了一个帐户,这是一个以色列域名注册器。然后我登录了。

登录个人概览区后,我尝试通过以下代码将自己移动到域管理区

window.location.href = "https://domains.livedns.co.il/DomainsList.aspx";

它在控制台中工作,但不是来自greasemonkey 脚本。

我想我可能需要在脚本中使用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 脚本中无效?

我不知道在这种情况下如何调试,因为我在运行脚本时在控制台中没有看到错误。

【问题讨论】:

标签: javascript debugging dom console href


【解决方案1】:

从错误的 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"  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多