javascript 将 window.addEventListener("load", function(), false); 等待浏览器自动填充字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12322822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WIll window.addEventListener("load", function(), false); wait for fields to be auto populated by the browser?
提问by RandomPrecision
I'm creating a GreaseMonkey script that will auto login to a page as long as the user has saved their username and password in the browser. It's pretty simple, it's just checks to make sure that the username field and the password field are not blank and then it clicks the login button automatically.
我正在创建一个 GreaseMonkey 脚本,只要用户在浏览器中保存了他们的用户名和密码,它就会自动登录到一个页面。这很简单,它只是检查以确保用户名字段和密码字段不为空,然后它会自动单击登录按钮。
Every now and then I was running in to an issue to where it didn't login. The page loaded and just sat there. I assumed it was simply due to the page not being fully loaded when the check of the username and password fields were done.
我不时遇到无法登录的问题。页面加载并就坐在那里。我认为这仅仅是因为在检查用户名和密码字段时页面没有完全加载。
Because of this, I added this to my script.
因此,我将其添加到我的脚本中。
window.addEventListener("load", Login(), false);
My question is... Will this actually wait for the browser to auto-fill those fields before attempting to login or is the page loading and the browser populating those fields 2 different actions?
我的问题是...在尝试登录之前,这实际上会等待浏览器自动填充这些字段,还是页面加载和浏览器填充这些字段 2 个不同的操作?
采纳答案by Jeremy J Starcher
Because there is no standard on how the auto-saved forms work, I would set up a timer on setTimeout()
因为没有关于自动保存表单如何工作的标准,我会在 setTimeout()
Er.. I was dumb. Current code does bad things if the person tries to enter their user information.
呃。。我傻了。如果此人试图输入他们的用户信息,当前代码会做坏事。
Untested, quick written code:
未经测试,快速编写的代码:
function logMeIn() {
var el = document.getElementById("username");
if (el && el.value !== "") {
// Finish the login
} else {
window.setTimeout(logMeIn, 200);
}
}
logMeIn();
Try 2:
尝试2:
// This is a User Script -- runs in its own encloser, won't pollute names back to the main document.
var loginTimer;
function logMeIn() {
var el = document.getElementById("username");
if (el && el.value !== "") {
// Finish the login
} else {
loginTimer = window.setTimeout(logMeIn, 200);
}
}
logMeIn();
// can't use ".onfocus" -- its a userscript.
// Cancel the timer if the username field gets focus -- if the user tries to enter things.
document.getElementById("username").addEventListner("focus") = function(e) {
if (loginTimer) {
window.clearTimeout(loginTimer);
}
}
回答by meder omuraliev
Did you mean to reference Login
instead of immediately executing it?
您的意思是引用Login
而不是立即执行吗?
window.addEventListener("load", Login, false);
Your way executes Login
beforethe window loads.
您的方式Login
在窗口加载之前执行。