-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
93 lines (77 loc) · 2.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const casual = require('casual-browserify')
const _EXCLUDED = [
'button',
'submit',
'hidden'
]
const containerButtonStyle = `
position: fixed;
background: white;
padding: 1rem;
top: 50px;
right: 50px;
z-index: 99999;
border: 1px solid black;
`
const buttonStyle = `
padding: 1rem;
font-size: 16px;
background: #ddd;
border: 1px solid black;
cursor: pointer;
`
const isExcluded = (el) => _EXCLUDED.includes(el)
const _ADITIONAL_PARAMS = {
zip: () => casual.zip(6),
lastname: () => casual.lastname,
firstname: () => casual.firstname
}
const isFunction = (f) => f instanceof Function
function findInputElements () {
if (typeof window === 'undefined') {
console.warning('Form autofill just works in client side')
return null
}
const inputs = document.querySelectorAll('form input')
const selects = document.querySelectorAll('form select')
const textAreas = document.querySelectorAll('form textArea')
return [...inputs, ...textAreas]
}
function fillElements (elements = [], defaultValues = {}) {
if (!elements.length) {
console.warning('cannot find DOM input elements')
return null;
}
elements.forEach(el => {
if (!isExcluded(el.type)) {
const value = casual[el.name]
if (el.name in defaultValues) {
el.value = defaultValues[el.name]
} else if (_ADITIONAL_PARAMS[el.name]) {
el.value = _ADITIONAL_PARAMS[el.name]()
} else if (value) {
el.value = value
} else {
el. value = (casual[el.type]) ? casual[el.type] : ''
}
}
})
}
const fill = (defaultValues = {}) => {
const elements = findInputElements()
fillElements(elements, defaultValues)
}
const tool = (defaultValues = {}) => {
const button = document.createElement('button')
button.textContent = 'Autofill'
button.setAttribute('style', buttonStyle)
button.onclick = () => fill(defaultValues)
const container = document.createElement('div')
container.setAttribute('style', containerButtonStyle)
container.appendChild(button)
document.querySelector('body').appendChild(container)
}
module.exports = {
fill,
tool
}