Skip to content

Instantly share code, notes, and snippets.

@WickyNilliams
Last active May 10, 2022 15:22
Show Gist options
  • Save WickyNilliams/eb6a44075356ee504dd9491c5a3ab0be to your computer and use it in GitHub Desktop.
Save WickyNilliams/eb6a44075356ee504dd9491c5a3ab0be to your computer and use it in GitHub Desktop.
formdata event polyfill
class FormDataEvent extends Event {
constructor(formData) {
super("formdata")
this.formData = formData
}
}
class FormDataPolyfilled extends FormData {
constructor(form) {
super(form)
this.form = form
form.dispatchEvent(new FormDataEvent(this))
}
append(name, value) {
let input = this.form.elements[name]
if (!input) {
input = document.createElement("input")
input.type = "hidden"
input.name = name
this.form.appendChild(input)
}
// if the name already exists, there is already a hidden input in the dom
// and it will have been picked up by FormData during construction.
// in this case, we can't just blindly append() since that will result in two entries.
// nor can we blindly delete() the entry, since there can be multiple entries per name (e.g. checkboxes).
// so we must carefully splice out the old value, and add back in the new value
if (this.has(name)) {
const entries = this.getAll(name)
const index = entries.indexOf(input.value)
if (index !== -1) {
entries.splice(index, 1)
}
entries.push(value)
this.set(name, entries)
} else {
super.append(name, value)
}
input.value = value
}
}
function supportsFormDataEvent({ document }) {
return 'FormDataEvent' in window
}
function polyfillFormDataEvent(win) {
if (!win.FormData || supportsFormDataEvent(win)) {
return
}
window.FormData = FormDataPolyfilled
win.addEventListener("submit", e => {
if (!e.defaultPrevented) {
// eslint-disable-next-line no-new
new FormData(e.target)
}
})
}
The MIT License (MIT)
Copyright (c) 2021 Nick Williams (https://wicky.nillia.ms)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment