Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

beforeunload-request

Package Overview
Dependencies
Maintainers
16
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

beforeunload-request

A unified API to reliably send data on beforeunload.

  • 1.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
16
Created
Source

beforeunload-request

A unified API to reliably send data on beforeunload.

Why

There is often a need to send data to a server before a page is closed. Asynchronous XHR requests aren't guaranteed to be sent in such a scenario, so traditionally developers have used synchronous XHR requests. However, due to the poor user experience that synchronous XHR requests on beforeunload cause, browsers have started disallowing them. There are alternatives to synchronous XHR (navigator.sendBeacon and fetch with keepalive), but these new APIs have their own set of quirks and browser issues.

This library unifies all available methods into a single API that prevents common pitfalls (see Methodology).

Installation

$ npm install beforeunload-request

Usage

import beforeunloadRequest from 'beforeunload-request';

const success = beforeunloadRequest(url, options);

Parameters

OptionDescriptionDefault
urlURL to send request to (required).
optionsRequestInit object. The entire object is passed to fetch, however, only the options listed below are considered for sendBeacon and XMLHttpRequest.
options.methodHTTP method to use.'POST'
options.headersObject of HTTP headers to use.null
options.bodyA string or BodyInit type for the data to send. No automatic conversion of any kind is done (e.g. you must convert to JSON or to URL encoded values yourself).null
options.credentialsA RequestCredentials string for the credentials mode to use.'include'

Return value

The function returns a boolean indicating if the request was successful, with one important caveat: if fetch is used, it will always return true; it's impossible to synchronously know if a fetch will result in an error. Otherwise, false guarantees the request did not go through.

Examples

Simple POST request

beforeunloadRequest('/flushSession');

PUT with JSON

beforeunloadRequest('/save', {
	method: 'PUT',
	body: JSON.stringify(data),
	headers: {
		'Content-Type': 'application/json'
	}
});

Using the return value

window.addEventListener('beforeunload', event => {
	const success = beforeunloadRequest('/save', {
		method: 'PUT',
		body: JSON.stringify(data),
		headers: {
			'Content-Type': 'application/json'
		}
	});

	if (!success) {
		// Show a warning that the user might lose data if they leave the page
		event.preventDefault();
		event.returnValue = '';
	}
});

Browser compatability

This library requires, at the minimum, support for XMLHttpRequest, including setRequestHeaders and withCredentials. Those are supported in IE10 and above.

Methodoloy

We first try to use navigator.sendBeacon if it's available and the request is compatible. Compatible requests are POST requests with 'include' as the credentials mode and no headers, with the exception of Content-Type if the data being sent is a string. navigator.sendBeacon can also fail if the data being sent is over the maximum size limit or due to a browser issue with Content-Type.

If navigator.sendBeacon is not available, if the request is not compatible, or if it otherwise fails, we then try to use synchronous XMLHttpRequest. Some browsers disallow synchronous XHR on beforeunload.

If synchronous XHR fails, we try fetch with the keepalive flag set. We do this after synchronous XHR because fetch with keepalive can fail in certain situations due to a browser issue with headers. This failure cannot be intercepted in a synchronous manner, so there is no way to recover with a different method.

This execution order ensures cross-browser compatability with, despite the quirks and issues with the new APIs. That being said, to guarantee the best user experience, you should aim for your requests to be compatible with navigator.sendBeacon. This avoids users having to wait for the synchronous XHR to complete when attempting to navigate away.

Keywords

FAQs

Package last updated on 10 Oct 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc