Skip to content

Instantly share code, notes, and snippets.

@kolodny
Last active February 23, 2019 17:43
Show Gist options
  • Save kolodny/130c200d9ff0f724160b to your computer and use it in GitHub Desktop.
Save kolodny/130c200d9ff0f724160b to your computer and use it in GitHub Desktop.
Save any form to autofill for development, supports dynamic content with {{ Math.random() }} syntax
http://kolodny.github.io/bookmarklet.html
document.body.addEventListener('click', go);
alert('click on a form element to get a bookmarklet of the saved form');
function go(event) {
var form = event.target;
while (form && form.tagName !== 'FORM') {
form = form.parentNode;
}
if (!form) {return;}
event.preventDefault();
document.body.removeEventListener('click', go);
var formSelector;
if (form.id) {
formSelector = '#' + form.id;
} else if (form.name) {
formSelector = 'form[name="' + form.name + '"]';
} else {
formSelector = 'form:nth-child(' + (Array.prototype.indexOf.call(document.forms, form) + 1) + ')'
}
var bookMarkletCode = "var form = document.querySelector('" + formSelector + "');\nvar inputIndex = -1;\nvar input;\n\n";
Array.prototype.forEach.call(form, function(elem, i) {
var code;
switch (elem.type) {
case 'reset':
case 'button':
case 'reset':
code = '';
break;
case 'select-multiple':
var selectedArray = Array.prototype.map.call(elem.options, function(option, i) {
return option.selected ? 1 : 0;
});
code = JSON.stringify(selectedArray) + '.forEach(function(selected, optionIndex) {\n\tinput.options[optionIndex].selected = !!selected\n})';
break;
case 'select-one':
code = 'input.selectedIndex = ' + elem.selectedIndex + ';';
break;
case 'radio':
case 'checkbox':
code = 'input.checked = ' + (elem.checked ? 'true' : 'false') + ';';
break;
default:
code = 'input.value = ' + JSON.stringify(elem.value).replace(/\{\{(.*?)\}\}/g, '" + $1 + "') + ';';
}
bookMarkletCode += 'input = form[++inputIndex]; /* input[' + i + '] */\n' + code + '\n\n';
});
var a = document.createElement('a');
a.href = 'javascript:(function(){\n' + escape(bookMarkletCode) + '\n})();'
a.innerText = 'Form Filler';
a.style.position = 'fixed';
a.style.top = 0;
a.style.left = 0;
a.style.zIndex = 99999;
a.style.background = 'green';
a.style.color = 'white'
a.style.padding = '10px';
a.onclick = function() {
document.body.removeChild(a);
};
document.body.insertBefore(a, document.body.firstChild);
alert('the bookmarklet is available at the top left of the page, drag to bookmarks bar to add, click to remove from DOM');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment