Skip to content

Commit

Permalink
Patch navigator.sendBeacon to use native FormData (#77)
Browse files Browse the repository at this point in the history
Fixes #74
  • Loading branch information
jimmywarting authored Mar 3, 2019
2 parents 1fc70db + fcc80b7 commit 3a7c148
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
11 changes: 11 additions & 0 deletions FormData.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ if (typeof Blob === 'function' && (typeof FormData === 'undefined' || !FormData.
// To be monkey patched
const _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
const _fetch = global.Request && global.fetch
const _sendBeacon = global.navigator && global.navigator.sendBeacon

// Unable to patch Request constructor correctly
// const _Request = global.Request
Expand Down Expand Up @@ -391,5 +392,15 @@ if (typeof Blob === 'function' && (typeof FormData === 'undefined' || !FormData.
}
}

// Patch navigator.sendBeacon to use native FormData
if (_sendBeacon) {
global.navigator.sendBeacon = function (url, data) {
if (data instanceof FormDataPolyfill) {
data = data['_asNative']()
}
return _sendBeacon.call(global.navigator, url, data)
}
}

global['FormData'] = FormDataPolyfill
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ A `FormData` polyfill

This polyfill conditionally replaces the native implementation rather then fixing the missing functions,
since otherwise there is no way to get or delete existing values in the FormData object.
Therefore this also patches `XMLHttpRequest.prototype.send` and `fetch` to send the FormData as a blob.
Therefore this also patches `XMLHttpRequest.prototype.send` and `fetch` to send the `FormData` as a blob,
and `navigator.sendBeacon` to send native `FormData`.

I was unable to patch the Response/Request constructor
so if you are constructing them with FormData you need to call `fd._blob()` manually.
Expand Down

0 comments on commit 3a7c148

Please sign in to comment.