问题
I use Windows10 home with latest Firefox and Greasemonkey.
I created an account in livedns.co.il, which is an Israeli domain register. I then logged in.
After logging in to the personal overview area, I tried to move myself to the domains management area, via this code:
window.location.href = "https://domains.livedns.co.il/DomainsList.aspx";
It worked in console but not from a greasemonkey script.
I thought I might need setTimeout()
in the script:
setTimeout(()=>{
window.location.href = "https://domains.livedns.co.il/DomainsList.aspx";
}, 1000);
but this code also worked only in console.
Steps to reproduce
After creating an account and logging in, this is the original pattern I used:
// ==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);
Just change username and password, then test.
My question
What makes a vanilla JavaScript code to work in console but not from a (greasemonkey) script? In particular, why does the changing of href of location of the document works only in console but not in a Greasemonkey script?
I don't know how to debug in such a case because I don't see an error in console when I run the script.
回答1:
I had a logical mistake when running the code from the wrong url (I should have ensured that I'm in https://domains.livedns.co.il/Main.aspx
to successfully run the code. I fixed that by using if-then conditionals (I'll find out if I'm having any significant security threat using this way).
Note how I changed the @include
and had richer usage of URLs.
// ==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"
}
来源:https://stackoverflow.com/questions/49720005/vanilla-javascript-code-works-in-console-but-not-from-a-greasemonkey-script