A handy wrapper for the Web Notifications API

Overview

Notify.js

Build Status

A handy wrapper for using the Web Notifications API. Notify.js aims to simplify requesting user permission and associated Web Notification API events, as well as providing a few extra callbacks and convenience methods.

Online demo: https://alexgibson.github.io/notify.js/

Installation

npm install notifyjs

Note: when installed via npm the Notify.js source file is located at ./dist/notify.js.

Build

Notify.js is written in ES6 and transpiled to ES5 & UMD format using Babel and Rollup.

Install dependencies:

npm install

Then build from source:

npm run build

Usage

To initialize a web notification create a new Notify instance, passing the message title as well as any other options you wish to use.

var myNotification = new Notify('Yo dawg!', {
	body: 'This is an awesome notification',
	notifyShow: onNotifyShow
});

function onNotifyShow() {
	console.log('notification was shown!');
}

Then show the notification.

myNotification.show();

It's a good idea to make sure that you have permissions to send notifications first.

if (!Notify.needsPermission) {
    doNotification();
} else if (Notify.isSupported()) {
    Notify.requestPermission(onPermissionGranted, onPermissionDenied);
}

function onPermissionGranted() {
	console.log('Permission has been granted by the user');
	doNotification();
}

function onPermissionDenied() {
	console.warn('Permission has been denied by the user');
}

Required parameters

  • title (string) - notification title

Optional parameters

All options supported in the Notifications API specification, in addition to:

  • timeout: (integer) - number of seconds to close the notification automatically
  • closeOnClick: (boolean) - close the notification when clicked. Useful in chrome where the notification remains open until the timeout or the x is clicked.
  • notifyShow: (function) - callback when notification is shown
  • notifyClose: (function) - callback when notification is closed
  • notifyClick: (function) - callback when notification is clicked
  • notifyError: (function) - callback when notification throws an error

Static methods and properties

  • Notify.requestPermission(onPermissionGrantedCallback, onPermissionDeniedCallback) - requests permission from the user if needed and handles permission callbacks.
  • Notify.isSupported - Function to test for Web Notifications API browser support
  • Notify.needsPermission - Boolean property to check if permission is needed for the user to receive notifications.

Instance methods

  • Notify.show - Function to display the Notify instance
  • Notify.close - Function to close the Notify instance

Test

In the project root, to perform a single pass of the tests using Firefox run:

npm run test

This will also automatically build from source before running the tests.

Demo example

An easy way to run the provided demo file is to use python SimpleHTTPServer and then navigate to the /example directory:

python -m SimpleHTTPServer

Browser support

http://caniuse.com/#search=notifications

Comments
  • Support mobile browsers through ServiceWorker

    Support mobile browsers through ServiceWorker

    Trying the notification API on Android, I ran into the following:

    http://stackoverflow.com/questions/29774836/failed-to-construct-notification-illegal-constructor

    Not sure about iOS support. I was wondering, are there any plans to support mobile browsers through the ServiceWorkerRegistration.showNotification() API? Especially since the Notification API may be removed in future versions of desktop Chrome. It seems to me that this library would be a great place to wrap all these different APIs and try to get a solution that works on most devices.

    enhancement 
    opened by perrin4869 40
  • Initial service worker api support

    Initial service worker api support

    Still quite a way to go, but the basics are here.

    Things working:

    • New extra options in Notify.js for Service Worker API
    • Notify.js works in service workers too if permission was granted

    TODO:

    • Testing (suggestions would be very much appreciated)
    • Update README.md
    • Event handling. Apparently show and close are being deprecated, different behavior on service workers, need more investigation.
    • Maybe we'll think of something else
    opened by perrin4869 19
  • Weird export since 2.x

    Weird export since 2.x

    Hey, I've updated to 2.0.2 and noticed that it exports differently. I'm using Babel + CommonJS Module Plugin. Since 2.0.2 I have to do the following:

    import Notify from 'notifyjs';
    if (Notify.default.needsPermission) {
      Notify.default.requestPermission();
    }
    

    Notice the default. - apparently it exports a Object that has a default member as default.

    opened by marudor 16
  • jspm not found

    jspm not found

    I think it's unreasonable for a package to require the user to manually install something to be able to use your package.

    Your package may depend on jspm if you want but I expect all package to be installable simply with a npm install.

    For instance, all my packages (see this one for instance) are transpiled to ES5 before publishing.

    opened by julien-f 15
  • Click function won't work if browser or page is not focused in Chrome

    Click function won't work if browser or page is not focused in Chrome

    yeah basically "Click function won't work if browser or page is not focused" the notification is just close. Is this function needs to be simple like window.open or something ?

    opened by berkaey 15
  • Add requiredInteraction support

    Add requiredInteraction support

    Our clients make heavy use of notifications and Chrome 47s removal of their notification center broke some things. This was my attempt to fix it. I thought I'd share if you'd like to use it.

    This PR:

    1. passes along the requiredInteraction field that Chrome respects
    2. adds a field to close the notification on click when a requiredInteraction is used (bug in chrome?)
    3. adds a hack to Firefox to continually call notifications when the requiredInteraction field is used until the user clicks it (ugly, but effective)
    opened by nslager 11
  • update to version 1.2.6 throws error in karma/PhantomJS

    update to version 1.2.6 throws error in karma/PhantomJS

    Hey guys, I am having an issue with notify.js when running unittests out of karma/PhantomJS after updating to to notify.js v1.2.6: ReferenceError: Can't find variable: Notification at /Users/beane/Code/debug-notify.js/bower_components/notify.js/notify.js:105

    screen shot 2015-09-25 at 3 52 38 pm

    This error is thrown before any of my tests run. Here are my dependency versions: "devDependencies": { "bower": "1.5.3", "jasmine-core": "2.3.4", "karma": "0.13.10", "karma-jasmine": "0.3.6", "karma-phantomjs-launcher": "0.2.1", "phantomjs": "1.9.18" }

    Demo here: https://github.com/ErikBean/debug-notify.js

    Any help with this would be great, as our dev team is stuck with the previous version until this gets resolved. Thanks, -Erik

    opened by ErikBean 11
  • Static functions

    Static functions

    Added Notify.isSupported(), Notify.needsPermission(), Notify.requestPermission() so we can call these functions without having to create a new Notify object.

    opened by superkarn 11
  • Doesn't work in Chrome on Android

    Doesn't work in Chrome on Android

    At least your demo page (http://alxgbsn.co.uk/notify.js/) displays notifications fine in desktop and mobile Firefox, as well as in desktop Chrome, but doesn't do anything neither in mobile Chrome, nor in Android default browser. I have tested it on:

    • Highscreen Alpha GT - Android 4.0.3, Chrome 30.0.1599.82
    • Digma iDxD10 - Android 4.0.4, Chrome 28.0.1500.94

    (I don't know how to look up the default browser's version). Please rectify, as I'm really looking forward to using your library. I'd be happy to provide assistance, if need be.

    opened by septagram 10
  • Different behaviour between Firefox on Debian and Windows

    Different behaviour between Firefox on Debian and Windows

    Hi,

    I have a strange behaviour with Notifications on Firefox. I use the version 45.0.1 both on Debian and Windows.

    This code shows up the notification on Windows but not on Debian:

    var Notify              = require("notifyjs");
    var prepareNotification = function () {
        var timeoutNotification = new Notify("Inactivité détectée", {
            body: "Vous serez déconnecté pour cause d'inactivité dans 60 secondes.",
            closeOnClick: true,
            timeout: 5,
            icon: "http://domain.tld/example.png"
        });
    
        timeoutNotification.show();
    };
    
    if (!Notify.needsPermission) {
        prepareNotification();
    } else if (Notify.needsPermission && Notify.isSupported()) {
        Notify.requestPermission(function () {
            prepareNotification();
        });
    }
    

    Your demo page works both on Windows and Debian: https://alexgibson.github.io/notify.js/

    All is working fine with Chrome.

    opened by DjLeChuck 9
  • Notify is not defined

    Notify is not defined

    it occures when write

    var myNotification = new Notify('Yo dawg!', { body: 'This is an awesome notification', notifyShow: onNotifyShow });

    function onNotifyShow() { console.log('notification was shown!'); }. it will give notify not define error ("i am not using require here").

    and if i use require like:

    var Notify = require('notifyjs') var myNotification = new Notify('Yo dawg!', { body: 'This is an awesome notification', notifyShow: onNotifyShow });

    function onNotifyShow() { console.log('notification was shown!'); }.

    then it shows /Volumes/Project data/node/demo/node_modules/notifyjs/dist/notify.js:63 var N = window.Notification; ^ window is not defined. please help

    awaiting feedback 
    opened by Aksh0377 7
  • Notify.js 4.0 - native ES module

    Notify.js 4.0 - native ES module

    This is more a heads up, but when I publish version 4.0 of this library I plan to:

    • Publish as a native ES module (all evergreen browsers now support modules natively).
    • Remove the transpiled version from the repo (removing both rollup and babel as dependencies).
    • Remove Bower support.

    If folks want the ES5 compatibility, they can still transpile using their own builds.

    opened by alexgibson 0
  • Remove useless error thrown

    Remove useless error thrown

    Knock Knock :door: anybody still here ? :smile:

    I noticed an error in our logs : You must only call this before calling Notification.requestPermission(), otherwise this feature detect would trigger an actual notification! and I know why it happens.

    The problem :

    Imagine a scenario where a user opens up a web chat app in two different browser tab. At some point the user receives a chat message and the app ask for permission to display web notifications. Since the app is realtime, it will ask for permission in BOTH tabs at the same time. The user may then click "allow" in the current tab and leave the other untouched.

    At this point, Notify.needsPermission will still be true in the other tab even if N.permission === 'granted', which will then lead us to calling Notify.isSupported() and triggering the error in the other tab when a new message is received.

    The fix :

    I think it's safe to assume that if the permission has been granted already, this feature MUST be supported ! Therefore we can just return true there, instead of throwing and error.

    In fact, to completely fix this scenario we would need to refactor Notify.needsPermission into a method/getter that checks if N.permission === 'granted' equals true instead of a boolean initialized on start :man_shrugging:

    opened by wmcmurray 6
  • Support Promise API

    Support Promise API

    The latest version of requestPermission deprecates the callback interface in favor of a Promise-based interface. This library should support the Promise-based interface as well.

    It looks like Safari doesn't currently support the Promise interface, but it should be possible for this library to have its requestPermission both take a callback and return a promise for backwards compatibility.

    enhancement 
    opened by turnerhayes 1
  • Use PageVisibility HTML5 API

    Use PageVisibility HTML5 API

    I think it might be a good idea to use PageVisibility API to display notifications only when page is not visible for example, like https://github.com/ttsvetko/HTML5-Desktop-Notifications

    Notify.config({
        pageVisibility: true|false
    })
    
    enhancement 
    opened by hardware 1
  • Timeout doesn't work in Firefox (31)

    Timeout doesn't work in Firefox (31)

    Firefox forces notifications to close after about 4 seconds regardless of the timeout option. It works fine in Chrome. This note may have something to do with it. Thanks!

    bug 
    opened by Noleli 6
Owner
Alex Gibson
Open Source, Web Standards, HTML, CSS, JavaScript, Node.js, Browsers
Alex Gibson
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A jQuery plugin wrapper around Bootstrap Alerts, to create Notifications (Toasts)

bootstrap-show-notification A jQuery plugin wrapper around Bootstrap 4 Alerts, to show them as toasts (also called notifications) dynamically from Jav

Stefan Haack 10 Aug 22, 2022
This app helps manage a bookstore. It comes in handy when you need to manage a personal book store or library. Entirely built on es6.

Awesome Books A Microverse project on learnong javascript. Additional description about the project and its features. Built With HTML5 CSS3 Javascript

Atugonza ( Billions ) Joel 13 Apr 22, 2022
The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day today activies. Check out the live demo.

Todo List App The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day toda

Atugonza ( Billions ) Joel 14 Apr 22, 2022
Adds a handy $parent magic property to your Alpine components.

✨ Help support the maintenance of this package by sponsoring me. Alpine $parent Access parent components using a handy $parent magic variable. This pa

Ryan Chandler 10 Aug 29, 2022
A handy-dandy JS shim to run OreUI files in your browser (to varying degrees of success.)

OreUIShim (C) Luminoso 2022 / MIT Licensed. Contributions Welcome! A small shim JS file to experiment with oreUI in the browser. How to use Prerequisi

null 12 Dec 8, 2022
Small PNG to WEBP converter, terminal based and handy for a frontend developer :D

Image Utils A small util i used while making antstack.com What does it do and how to use? It basically converts .png files to .webp Read about Webp he

Pruthvi Shetty 6 Aug 24, 2022
JustGage is a handy JavaScript plugin for generating and animating nice & clean dashboard gauges. It is based on Raphaël library for vector drawing.

JustGage JustGage is a handy JavaScript plugin for generating and animating nice & clean dashboard gauges. It is based on Raphaël library for vector d

Bojan Djuricic 1.8k Jan 3, 2023
A handy little app for copying & pasting images.

PikPicPASTE A handy little app for copying & pasting images. Usage Click and drag the hamburger tile to move the toolbar Click the hamburger tile to s

null 5 Nov 1, 2022
This is a jquery ui sortable helper plugin for handy tree type structure sotable.

Tree Sortable A drag and drop list item sorting and level changing library. Motivation The jQuery-ui's sortable plugin allows us to sort items vertica

Sajeeb Ahamed 10 Dec 23, 2022
This is a bot for Telegram that can be used to receive webhook notifications from Gitlab. It is built with the Next.js API.

Telegram Bot for Gitlab Webhook ?? Note This project is still in development. Just relax ?? This is a bot for Telegram that can be used to receive web

M. Zakiyuddin Munziri 2 Oct 22, 2022
A Javascript based web application for monitoring, analytics and notifications

JELLYWATCH Jellywatch is a javascript web application for monitoring*, analytics** and notifications** inspired by tautulli for Jellyfin/Emby Media Se

null 27 Dec 28, 2022
Fnon is a client-side JavaScript library for models, loading indicators, notifications, and alerts which makes your web projects much better.

???????? Fnon is the name of my late mother, It's an Arabic word which means Art, I created this library in honor of her name. Fnon is a client-side J

Adel N Al-Awdy 5 Sep 11, 2022
Subscribe to rss feeds from anywhere, receive notifications from anywhere.

INK RSS 管理订阅,接收通知 示例网页 · 示例群组 · 报告Bug 介绍 特点 项目背景 TODO 注意事项 部署 额外附赠 使用建议 调查 贡献 作者 协议 介绍 INK RSS 提供及时且多样的 rss 通知服务,借助现有的接口你可以在任意位置订阅,并使用任意方式接收通知,并且所有服务均

null 253 Dec 28, 2022
Finding RATs is hard. Push notifications for findarat.com.au

RAT-Push-Notifications Finding RATs is hard. Push notifications for findarat.com.au What is this? This is a script that will run on your computer / se

Richard S 3 Jan 13, 2022
Polkadot Basic Notifications

A dead-simple, yet highly effective notification system for Polkadot and its parachains (or, any substrate-based chain, most specifically).

Kian Paimani 38 Jan 2, 2023
A javascript framework for developing pretty browser dialogs and notifications.

AlertifyJS AlertifyJS is a javascript framework for developing pretty browser dialogs and notifications. AlertifyJS is an extreme makeover of alertify

Mohammad Younes 2k Jan 2, 2023
ToDo list for your GitHub notifications. Available on MacOS.

GitToDo Streamline your workflow, stay on top of issues and pull requests. ToDo list for your GitHub notifications. Available on MacOS. Features Menu

Rushat Gabhane 2 Jun 14, 2022