Prefilling Forms With a Custom Bookmarklet
Jump to navigation
Jump to search
Source[edit]
This is based on an article on CSS-Tricks.
Bookmark[edit]
The code for the bookmark:
(function(d) {
var body = d.getElementsByTagName('body')[0],
script = d.createElement('script');
script.src = '//localhost.com/pathtomyfile.js';
body.appendChild(script);
}(window.document));
Compressed:
(function(d){var body=d.getElementsByTagName('body')[0],script=d.createElement('script');script.src='//localhost.com/path/to/my/file.js';body.appendChild(script)}(window.document));
Replace //localhost.com/path/to/my/file.js with the URL to the JavaScript source specific to the form to be tested.
Precede the code with javascript: and save it as the URL for the bookmark.
JavaScript[edit]
The code for filling the form gets saved at //localhost.com/path/to/my/file.js:
(function(win, doc, $, undefined) {
'use strict';
// Don't run if jQuery isn't loaded
if (typeof window.jQuery === 'undefined') {
return;
}
var _rand = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$.getScript('//cdnjs.cloudflare.com/ajax/libs/Faker/0.7.2/MinFaker.js')
.done(function() {
fillForm();
})
.fail(function() {
win.console.error('ERROR: FakerJS not loaded!');
});
/**
* create data object
*/
var FormData = function(faker) {
this.faker = faker;
this.first_name = 'Damien';
this.last_name = 'Barchowsky';
this.phone = faker.PhoneNumber.phoneNumber();
this.email = 'dbarchowsky@yahoo.com';
this.application = faker.Lorem.paragraphs(3);
};
/**
* fill in the form
*/
var fillForm = function() {
var data = new FormData(window.Faker);
$('input[name="bfna"]').val(data.first_name);
$('input[name="blna"]').val(data.last_name);
$('input[name="lipho"]').val(data.phone);
$('input[name="bema"]').val(data.email);
$('textarea[name="cshi"]').val(data.application);
};
}(window, window.document, window.jQuery));
Replace the logic in the FormData object and fillForm() routine to make it apply to the form to be tested.
Additional resources[edit]
The page containing the form must also load the jQuery libraries for this to work.
There is some additional useful code for setting checkboxes and dropdowns at the orignal link.