Window.fetch polyfill

Overview

window.fetch polyfill

This project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to uphold this code. [code-of-conduct]: http://todogroup.org/opencodeofconduct/#fetch/[email protected]

The global fetch function is an easier way to make web requests and handle responses than using an XMLHttpRequest. This polyfill is written as closely as possible to the standard Fetch specification at https://fetch.spec.whatwg.org.

Installation

Available on Bower as fetch.

$ bower install fetch

You'll also need a Promise polyfill for older browsers.

$ bower install es6-promise

This can also be installed with npm.

$ npm install whatwg-fetch --save

For a node.js implementation, try node-fetch.

For use with webpack, add this package in the entry configuration option before your application entry point:

entry: ['whatwg-fetch', ...]

For babel and es2015+, make sure to import the file:

import 'whatwg-fetch';
fetch(...);

Usage

The fetch function supports any HTTP method. We'll focus on GET and POST example requests.

HTML

fetch('/users.html')
  .then(function(response) {
    return response.text()
  }).then(function(body) {
    document.body.innerHTML = body
  })

JSON

fetch('/users.json')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Response metadata

fetch('/users.json').then(function(response) {
  console.log(response.headers.get('Content-Type'))
  console.log(response.headers.get('Date'))
  console.log(response.status)
  console.log(response.statusText)
})

Post form

var form = document.querySelector('form')

fetch('/users', {
  method: 'POST',
  body: new FormData(form)
})

Post JSON

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})

File upload

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

Caveats

The fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:

  • The Promise returned from fetch() won't reject on HTTP error status even if the response is a HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure, or if anything prevented the request from completing.

  • By default, fetch won't send any cookies to the server, resulting in unauthenticated requests if the site relies on maintaining a user session.

Handling HTTP error statuses

To have fetch Promise reject on HTTP error statuses, i.e. on any non-2xx status, define a custom response handler:

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })

Sending cookies

To automatically send cookies for the current domain, the credentials option must be provided:

fetch('/users', {
  credentials: 'same-origin'
})

This option makes fetch behave similar to XMLHttpRequest with regards to cookies. Otherwise, cookies won't get sent, resulting in these requests not preserving the authentication session.

Use the include value to send cookies in a cross-origin resource sharing (CORS) request.

fetch('https://example.com:1234/users', {
  credentials: 'include'
})

Receiving cookies

Like with XMLHttpRequest, the Set-Cookie response header returned from the server is a forbidden header name and therefore can't be programatically read with response.headers.get(). Instead, it's the browser's responsibility to handle new cookies being set (if applicable to the current URL). Unless they are HTTP-only, new cookies will be available through document.cookie.

Obtaining the Response URL

Due to limitations of XMLHttpRequest, the response.url value might not be reliable after HTTP redirects on older browsers.

The solution is to configure the server to set the response HTTP header X-Request-URL to the current URL after any redirect that might have happened. It should be safe to set it unconditionally.

# Ruby on Rails controller example
response.headers['X-Request-URL'] = request.url

This server workaround is necessary if you need reliable response.url in Firefox < 32, Chrome < 37, Safari, or IE.

Browser Support

Chrome Firefox IE Opera Safari
Latest Latest 10+ Latest 6.1+
You might also like...

A prototype snap for injecting gas fee prices into a confirmation window that also serves as the basis for a 5-minute Snaps tutorial

A prototype snap for injecting gas fee prices into a confirmation window that also serves as the basis for a 5-minute Snaps tutorial

@Montoya/gas-fee-snap A simple Snap example based on @MetaMask/template-snap. Read below for a tutorial! Prerequisites Before you begin, make sure you

Dec 8, 2022

This tool uses native browser APIs to take screenshots of a given web page, tab, window, or the user's entire screen.

This tool uses native browser APIs to take screenshots of a given web page, tab, window, or the user's entire screen.

This tool uses native browser APIs to take screenshots of a given web page, tab, window, or the user's entire screen.

Jan 1, 2023

An accessible dialog window library for all humans.

An accessible dialog window library for all humans.

Version 0.4.4 Requires jQuery 1.11.2 or higher (v2 not tested, v3 works but not extensively stress tested). Built by Humaan Modaal Modaal is a WCAG 2.

Dec 26, 2022

Finer control of the Obsidian sidebars. To be used with an external window manager.

Finer control of the Obsidian sidebars. To be used with an external window manager.

Sidebar Toggler Finer control of the Obsidian sidebars. To be used with an external window manager. What the plugin does It adds four commands for tog

Nov 4, 2022

A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.

Amuchina A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebW

Sep 17, 2022

Simulating raindrops falling on a window

RainyDay.js A simple script for simulating raindrops falling on a glass surface. Project Page How to use Just add script to page and initilize RainyDa

Nov 7, 2022

A simple JavaScript library, to display a window inside of the browser

A simple JavaScript library, to display a window inside of the browser

WindowJS WindowJS is a simple JavaScript library, to display a functional window inside of the browser. Demo: prod.thalmann.it/windowjs/demo.html Navi

Dec 14, 2022

A simple JS example for NextAuth Google login with a popup window instead of redirect.

A simple JS example for NextAuth Google login with a popup window instead of redirect.

Dec 7, 2022

Test utility to mock `window.matchMedia` for JSDOM environments.

mock-match-media Test utility for mocking window.matchMedia in JSDOM environments. JSDOM doesn't provide support for window.matchMedia, which means te

Oct 12, 2022
Owner
Create more from https://github.com/fis-components/components
null
Use plain functions as modifiers. Polyfill for RFC: 757 | Default Modifier Manager

Use plain functions as modifiers. Polyfill for RFC: 757 | Default Modifier Manager

null 7 Jan 14, 2022
Polyfill to remove click delays on browsers with touch UIs

FastClick FastClick is a simple, easy-to-use library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile

FT Labs 18.8k Jan 2, 2023
Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill).

@sanity/client Javascript client for Sanity. Works in node.js and modern browsers (older browsers needs a Promise polyfill). Requirements Sanity Clien

Sanity 23 Nov 29, 2022
PouchDB for Deno, leveraging polyfill for IndexedDB based on SQLite.

PouchDB for Deno PouchDB for Deno, leveraging polyfill for IndexedDB based on SQLite. Usage import PouchDB from 'https://deno.land/x/[email protected]

Aaron Huggins 19 Aug 2, 2022
Polyfill `error.cause`

Polyfill error.cause. error.cause is a recent JavaScript feature to wrap errors. try { doSomething() } catch (cause) { throw new Error('message',

ehmicky 4 Dec 15, 2022
A polyfill for ES6-style Promises

ES6-Promise (subset of rsvp.js) This is a polyfill of the ES6 Promise. The implementation is a subset of rsvp.js extracted by @jakearchibald, if you'r

Stefan Penner 7.3k Dec 28, 2022
Fast and lightweight dependency-free vanilla JavaScript polyfill for native lazy loading / the awesome loading='lazy'-attribute.

loading="lazy" attribute polyfill Fast and lightweight vanilla JavaScript polyfill for native lazy loading, meaning the behaviour to load elements rig

Maximilian Franzke 571 Dec 30, 2022
An extensible HTML DOM window manager with a professional look and feel

Wingman An extensible HTML DOM window manager with a professional look and feel. Installation Wingman only requires two files: wingman.css and wingman

nethe550 1 Jan 21, 2022
Tools for Dump NUXT JS Environment Config Through Browser Window Object

Introduction Nuxt JS is an open source javascript framework making web development simple and powerful. This tool is used to get environment configura

Agus Setya R 7 Sep 5, 2022
A simple cmatrix-like terminal decoration written in JavaScript that supports window resizing.

jsmatrix A simple cmatrix-like terminal decoration written in JavaScript that supports window resizing. Getting Started Dependencies NodeJS Any termin

Fülöp Tibor 7 Mar 27, 2022