Skip to content

Instantly share code, notes, and snippets.

@line0
Last active November 29, 2015 16:28
Show Gist options
  • Save line0/210315f4f94d3caf4e7a to your computer and use it in GitHub Desktop.
Save line0/210315f4f94d3caf4e7a to your computer and use it in GitHub Desktop.
Fetch polyfill (https://github.com/github/fetch) stripped down to provide GM_fetch via GM_XHR.
(function() {
'use strict';
var support = {
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob();
return true
} catch(e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
}
function headers(xhr) {
var head = new Headers()
var pairs = xhr.getAllResponseHeaders().trim().split('\n')
pairs.forEach(function(header) {
var split = header.trim().split(':')
var key = split.shift().trim()
var value = split.join(':').trim()
head.append(key, value)
})
return head
}
self.GM_fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request
if (Request.prototype.isPrototypeOf(input) && !init) {
request = input
} else {
request = new Request(input, init)
}
var xhr = new GM_XHR()
function responseURL() {
if ('responseURL' in xhr) {
return xhr.responseURL
}
// Avoid security warnings on getResponseHeader when not allowed by CORS
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL')
}
return;
}
xhr.onload = function() {
var status = (xhr.status === 1223) ? 204 : xhr.status
if (status < 100 || status > 599) {
reject(new TypeError('Network request failed'))
return
}
var options = {
status: status,
statusText: xhr.statusText,
headers: headers(xhr),
url: responseURL()
}
var body = 'response' in xhr ? xhr.response : xhr.responseText;
resolve(new Response(body, options))
}
xhr.onerror = function() {
reject(new TypeError('Network request failed'))
}
xhr.open(request.method, request.url, true)
if (request.credentials === 'include') {
xhr.withCredentials = true
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob'
}
for (let header of request.headers) {
xhr.setRequestHeader(header[0], header[1]);
}
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
})
}
self.GM_fetch.polyfill = true
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment