Using Javascript to Open a New Page and Populate Form Values There
I am using JavaScript in a bookmarklet to populate form elements on a website:
javascript:var f = document.forms[0];
f.getElementsByTagName('input')[0].value = 'myname';
f.getElementsByTagName('input')[1].value = 'mypassword';
f.getElementsByTagName('input')[2].click
This works. However what I would like to create is a bookmarklet so that it opens the target page, and populates the values there; however it seems that onces the page is loaded, other JavaScript codes are not executed. So, the following doesn't work.
javascript:window.location("mywebsite");var f = document.forms[0];
f.getElementsByTagName('input')[0].value = 'myname';
f.getElementsByTagName('input')[1].value = 'mypassword';
f.getElementsByTagName('input')[2].click;
I have also experimented with setTimeout to delay the execution of my code, but that didn't work.
javascript:var f = document.forms[0];setTimeout("f.getElementsByTagName('input')[0].value = 'myname';f.getElemen开发者_开发问答tsByTagName('input')[1].value = 'mypassword';f.getElementsByTagName('input')[2].click;",1000);
How can I load my script once I know the target page is fully loaded?
I don't use GreaseMonkey as a personal rule, to code for browsers that shouldn't use it. Bookmarklets are a least-common-denominator approach to automate logins when your system is locked down and won't allow install of Greasemonkey, Roboform, etc.
I've coded a lot of login bookmarklets and thought about what you're trying to do: add some script that gets executed after a page loads. I came to this page looking for the solution, but now I'm glad it doesn't work.
Think about the security implications of this. If it were possible to echo keystrokes to to a loaded page, it would also be able to listen to keystrokes and send them elsewhere -- very bad.
If you want to automate logins, try a bookmarklet pattern like this (remove line breaks):
javascript:
u='my_username';
p='my_password';
l='https://my_server/signon.aspx';
if(location!=l)location=l;
else{
g=document.getElementById;
ue=(g('username') || g('userid') || g('login_name'));
if(ue){
ue.value=u;
pe=(g('password') || g('pw') || g('pin'));
pe.value = p;
b=(g('submit_button') || g('signon_button') || g('login_button'));
document.close();
if(b)b.click();
}
}
Clicking the link once takes you to the signon.aspx page. Once the username field is available on the loaded page, clicking the same link again will fill the form and submit.
So it's one more click than you hoped, but if you put the bookmarklet on a toolbar it's hardly any delay. Good luck!
Greasemonkey is built into Chrome, sounds like you are trying to reinvent the wheel. Install a JS file and it will run when the page loads.
精彩评论