Time-Saving JavaScript Browser Bookmarks

Today I was sent the following JavaScript

javascript:(function(){$('#UserName').val('a_user');$('#Password').val('their_password');$('form').submit();})();

As it turns out, the JavaScript was actually intended to be a browser bookmark that, when clicked, auto-filled fields on the page and submitted it.

Let’s look at it more carefully. If we assume that the page has a:

  • Textbox with ID ‘UserName’.
  • Textbox with ID ‘Password’.
  • Form submit button.

When the above JavaScript is added as a browser bookmark (i.e. is set as the bookmark URL) you can click on it to autofill the boxes on the form and then have it submit it for you.

So, when I click on the browser bookmark, the script will:

  • Populate ‘UserName’ control with ‘a_user’.
  • Populate ‘Password’ control with ‘their_password’.
  • Submit the form.

If you find yourself having to repeatedly enter the same details on a form, simply create some JavaScript to populate it automatically, and add it as a bookmark. The example above is simple, but when you have dozens of fields then this can be a handy time-saving activity.

As an esteemed colleague quite rightly pointed out, the code makes two important assumptions:

  1. You are using jQuery
  2. The fields have IDs

If you’re not using jQuery, then simply using document.getElementById will suffice. There are also ways of getting elements without IDs, but if you do have control over the HTML then I would suggest adding them in anyway.

Leave a Reply