Form Submit Run JavaScript
I have been googling the phrase above for most of last night, and some of this morning, trying to find a good way to execute a JavaScript function from an HTML form. The reason: because the input type, “password” is only available in HTML and the text of a JavasScript prompt cannot be hidden or masked.
I know that passwords and JavaScript are a bad idea, because JavaScript runs client-side, but if the only thing I can control is client-side code, then I don’t have much choice. I’ll come back to this in a little bit.
How to run a JavaScript function from an HTML form:
I have found two ways to do it that seem fairly consistent. The first involves an onsubmit event in the form tag, and the second refers to a JavaScript function in the action attribute of the form.
<script language="javaScript" type="text/javascript"> function runJsFunction() { alert("you ran the js Function from the Form"); } </script> <form action="#" method="get" onsubmit="return runJsFunction()"> <input type="text" /> <input type="submit" value="Enter" /> </form>
The second method I like more, because it seems to be more versatile. I was working on a site where I could use my own HTML, but only in a div, inside of whatever framework that was going to hold my content. In my case, the first method, with the onsubmit event, failed to run the JavaScript correctly.
<script language="javaScript" type="text/javascript"> function runJsFunction() { alert("you ran the js Function from the Form"); } </script> <form action="javascript:runJsFunction();"> <input type="text" /> <input type="submit" value="Enter" /> </form>
Here are two ways to run JavaScript from a form. And now the caveats:
You probably shouldn’t actually use this tool for submitting passwords to a JavaScript function. Passwords would ideally be handled by a language that runs server-side.
If you are going to use this, as I am, for passwords, make sure you use CryptoJS. This will allow you to hash your password, so (malicious) people/users cannot see your password simply by looking at the page source.
Lastly, if you are going to use JavaScript to handle access to a specific web page, you probably don’t want that web page in the page source either. Once again, bad actors can view your page source and skip the whole authentication process, and just go straight to your web page.
One way of preventing this would be to set the inside page so that it’s only accessible via the authentication page. I don’t know how to do this yet.
Another method would be to use symmetric encryption to hide the inside page URL, and have the user enter the correct passphrase to decrypt the URL, followed by redirecting the user to the inside page. I don’t know how to this yet either.
So that leaves a project for the furture! =)