Greasemonkey doesn't recognize names

ellescuba27

Member
Messages
273
Reaction score
3
Points
18
I wanted to share a tip with you about Greasemonkey browser addon for Firefox which doesn't happen in Tampermonkey browser addon for Google Chrome, which does a similar job - they both run what's known as a userscript.
When developing userscripts, you are going to come accross websites from 1997 or so which still use the html name attribute in Javascript. Like this:
HTML:
<form name="form1">
<input type="text" name="userName" value=""></input>
</form>
While it could be useful for serversides like PHP, the obvious way to handle this in a userscript would be like this:
Code:
// wrong way, this won't work in Greasemonkey
document.form1.userName.value = "ellescuba27";
Obviously, this is a very old, outdated method (or somebody decided it was anyways). They should be using an ID attribute. But, this is an old site you want to create a userscript for, when ID attributes weren't useful yet.
But not only that, THIS DOESN'T WORK IN GREASEMONKEY. Somebody developing Greasemonkey must have thought it was so old and outdated, they didn't even bother to put it in!
So how can I make this work in Greasemonkey? Well, just do something like this, with getElementsByTagName!
Code:
// it works in Greasemonkey!
document.getElementsByTagName("input")[0].value = "ellescuba27";
And tada! It works in Greasemonkey! Only problem: you may have to update the script if the old site finally decides it's time for a change in design!
Hope this helps!
 

essellar

Community Advocate
Community Support
Messages
3,295
Reaction score
227
Points
63
Let's hope that you still run across JavaScript that uses the name attribute for form elements, since you can't get checkbox or radio button collections directly without it. It's just the implicit use of name in the dot-chain syntax that's the problem. This will work:

Code:
// for text and similar
document.forms["form_name"].elements["field_name"].value = "Your value here";
var someVariable = document.forms["form_name"].elements["field_name"].value;
 
Top