https://github.com/pubkey/unload
Run a piece of code when the javascript process stops. Works in all environments (browsers, nodejs..)
https://github.com/pubkey/unload
browser exitcode nodejs unload
Last synced: about 2 months ago
JSON representation
Run a piece of code when the javascript process stops. Works in all environments (browsers, nodejs..)
- Host: GitHub
- URL: https://github.com/pubkey/unload
- Owner: pubkey
- License: apache-2.0
- Created: 2016-12-08T14:49:54.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2025-05-02T01:35:26.000Z (2 months ago)
- Last Synced: 2025-05-02T02:36:48.821Z (2 months ago)
- Topics: browser, exitcode, nodejs, unload
- Language: JavaScript
- Homepage:
- Size: 201 KB
- Stars: 55
- Watchers: 2
- Forks: 10
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# javascript: unload
Run a piece of code whenever the javascript process stops/exits/quits. On **browsers, nodejs, electron, react-native, workers, iframes**. It also ensures that the exit-function is called only **once**.
You should use this module when your write a npm library where you dont know in which environments the users will run it.
# What does `unload` handle?
When nodejs:
```js
process.on('beforeExit');
process.on('exit');
process.on('SIGINT'); // catches ctrl+c event
process.on('uncaughtException'); // catches uncaught exceptions
```When browser:
```js
window.addEventListener('beforeunload'); // closing of normal browser-window
window.addEventListener('unload'); // closed inside of iframe
```# Usage
Installation:
`npm install unload --save`
Add a function which runs when the process exits:
```javascript
var unload = require('unload');
unload.add(function(){
console.log('Ouch, I\'m dying.');
});
```Add and remove the function (It will no longer run when the process exits):
```javascript
var unload = require('unload');
var ret = unload.add(function(){
console.log('Ouch, I\'m dying.');
});ret.remove(); // removes the event-handler
```Run all previously added functions:
```javascript
var unload = require('unload');
unload.add(function(){
console.log('Ouch, I\'m dying.');
});unload.runAll();
```Remove all added functions (They will no longer run when the process exits):
```javascript
var unload = require('unload');
unload.add(function(){
console.log('Ouch, I\'m dying.');
});unload.removeAll();
```# Sponsored by