├── .config └── karma.conf.js ├── .editorconfig ├── .eslintrc.js ├── .gitattributes ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ └── ci.yml ├── .gitignore ├── .jsbeautifyrc ├── .npmignore ├── .stylelintrc.json ├── LICENSE ├── README.md ├── bower.json ├── docs ├── CHANGELOG.md ├── api.md ├── example │ ├── example.css │ └── example.js ├── index.html └── service-worker.js ├── inch.json ├── package.json ├── test ├── helpers │ └── notify-mock.js └── spec │ └── web-notification-spec.js └── web-notification.js /.config/karma.conf.js: -------------------------------------------------------------------------------- 1 | /*global module: false, require: false */ 2 | 3 | module.exports = function (config) { 4 | 'use strict'; 5 | 6 | const mainJSFile = require('../package.json').main; 7 | 8 | config.set({ 9 | basePath: '../', 10 | frameworks: [ 11 | 'mocha', 12 | 'sinon-chai' 13 | ], 14 | port: 9876, 15 | logLevel: config.LOG_INFO, 16 | autoWatch: false, 17 | browsers: [ 18 | 'ChromiumHeadless' 19 | ], 20 | singleRun: false, 21 | reporters: [ 22 | 'progress', 23 | 'coverage' 24 | ], 25 | preprocessors: { 26 | [mainJSFile]: [ 27 | 'coverage' 28 | ] 29 | }, 30 | coverageReporter: { 31 | dir: 'coverage', 32 | reporters: [ 33 | { 34 | type: 'lcov', 35 | subdir: '.' 36 | } 37 | ], 38 | check: { 39 | global: { 40 | statements: 100, 41 | functions: 100, 42 | lines: 100, 43 | branches: 100 44 | } 45 | } 46 | }, 47 | customLaunchers: { 48 | ChromeHeadlessCI: { 49 | base: 'ChromeHeadless', 50 | flags: [ 51 | '--no-sandbox' 52 | ] 53 | } 54 | }, 55 | files: [ 56 | 'test/helpers/**/*.js', 57 | mainJSFile, 58 | 'test/spec/**/*.js' 59 | ] 60 | }); 61 | }; 62 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | indent_style = space 10 | indent_size = 4 11 | 12 | [*.json] 13 | indent_size = 2 14 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'env': { 3 | 'browser': true, 4 | 'commonjs': true, 5 | 'es2021': true, 6 | 'mocha': true 7 | }, 8 | 'extends': 'eslint:recommended', 9 | 'parserOptions': { 10 | 'ecmaVersion': 13 11 | }, 12 | 'rules': { 13 | 'indent': [ 14 | 'error', 15 | 4 16 | ], 17 | 'linebreak-style': [ 18 | 'error', 19 | 'unix' 20 | ], 21 | 'quotes': [ 22 | 'error', 23 | 'single' 24 | ], 25 | 'semi': [ 26 | 'error', 27 | 'always' 28 | ] 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | 4 | ## Issues 5 | 6 | Found a bug? Got a question? Want some enhancement?
7 | First place to go is the repository issues section, and I'll try to help as much as possible. 8 | 9 | ## Pull Requests 10 | 11 | Fixed a bug or just want to provided additional functionality?
12 | Simply fork this repository, implement your changes and create a pull request.
13 | Few guidelines regarding pull requests: 14 | 15 | * This repository is integrated with github actions for continuous integration.
16 | 17 | Your pull request build must pass (the build will run automatically).
18 | You can run the following command locally to ensure the build will pass: 19 | 20 | ````sh 21 | npm test 22 | ```` 23 | 24 | * This library is using multiple code inspection tools to validate certain level of standards.
The configuration is part of the repository and you can set your favorite IDE using that configuration.
You can run the following command locally to ensure the code inspection passes: 25 | 26 | ````sh 27 | npm run lint 28 | ```` 29 | 30 | * There are many automatic unit tests as part of the library which provide full coverage of the functionality.
Any fix/enhancement must come with a set of tests to ensure it's working well. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: sagiegurari 7 | 8 | --- 9 | 10 | ### Describe The Bug 11 | 12 | 13 | ### To Reproduce 14 | 15 | 16 | ### Error Stack 17 | 18 | ```console 19 | The error stack trace 20 | ``` 21 | 22 | ### Code Sample 23 | 24 | ```js 25 | // paste code here 26 | ``` 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: sagiegurari 7 | 8 | --- 9 | 10 | ### Feature Description 11 | 12 | 13 | ### Describe The Solution You'd Like 14 | 15 | 16 | ### Code Sample 17 | 18 | ```js 19 | // paste code here 20 | ``` 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | env: 4 | CLICOLOR_FORCE: 1 5 | jobs: 6 | ci: 7 | name: CI 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | - name: Install Chrome 15 | uses: browser-actions/setup-chrome@latest 16 | - name: Install Dependencies 17 | run: npm install 18 | - name: Run CI 19 | run: npm test 20 | - name: Coveralls 21 | uses: coverallsapp/github-action@master 22 | with: 23 | github-token: ${{ secrets.GITHUB_TOKEN }} 24 | path-to-lcov: './coverage/lcov.info' 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .temp 3 | node_modules 4 | bower_components 5 | npm-debug.log 6 | package-lock.json 7 | .nyc_output 8 | coverage 9 | -------------------------------------------------------------------------------- /.jsbeautifyrc: -------------------------------------------------------------------------------- 1 | { 2 | "js": { 3 | "indent_size": 4, 4 | "indent_char": " ", 5 | "eol": "\n", 6 | "indent_level": 0, 7 | "indent_with_tabs": false, 8 | "preserve_newlines": true, 9 | "max_preserve_newlines": 2, 10 | "space_in_paren": false, 11 | "jslint_happy": true, 12 | "space_after_anon_function": true, 13 | "brace_style": "collapse", 14 | "break_chained_methods": false, 15 | "keep_array_indentation": true, 16 | "unescape_strings": false, 17 | "wrap_line_length": 0, 18 | "end_with_newline": true, 19 | "comma_first": false, 20 | "eval_code": false, 21 | "keep_function_indentation": false, 22 | "space_before_conditional": true, 23 | "good_stuff": true 24 | }, 25 | "css": { 26 | "indent_size": 2, 27 | "indent_char": " ", 28 | "indent_with_tabs": false, 29 | "eol": "\n", 30 | "end_with_newline": true, 31 | "selector_separator_newline": false, 32 | "newline_between_rules": true 33 | }, 34 | "html": { 35 | "indent_size": 4, 36 | "indent_char": " ", 37 | "indent_with_tabs": false, 38 | "eol": "\n", 39 | "end_with_newline": true, 40 | "preserve_newlines": true, 41 | "max_preserve_newlines": 2, 42 | "indent_inner_html": true, 43 | "brace_style": "collapse", 44 | "indent_scripts": "normal", 45 | "wrap_line_length": 0, 46 | "wrap_attributes": "auto", 47 | "wrap_attributes_indent_size": 4 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | target 2 | .temp 3 | .nyc_output 4 | .config 5 | coverage 6 | bower_components 7 | .github 8 | test 9 | example 10 | -------------------------------------------------------------------------------- /.stylelintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "stylelint-config-standard" 3 | } 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simple-web-notification 2 | 3 | [![NPM Version](http://img.shields.io/npm/v/simple-web-notification.svg?style=flat)](https://www.npmjs.org/package/simple-web-notification) [![CI](https://github.com/sagiegurari/simple-web-notification/workflows/CI/badge.svg?branch=master)](https://github.com/sagiegurari/simple-web-notification/actions) [![Coverage Status](https://coveralls.io/repos/sagiegurari/simple-web-notification/badge.svg)](https://coveralls.io/r/sagiegurari/simple-web-notification) [![Known Vulnerabilities](https://snyk.io/test/github/sagiegurari/simple-web-notification/badge.svg)](https://snyk.io/test/github/sagiegurari/simple-web-notification) [![Inline docs](http://inch-ci.org/github/sagiegurari/simple-web-notification.svg?branch=master)](http://inch-ci.org/github/sagiegurari/simple-web-notification) [![License](https://img.shields.io/npm/l/simple-web-notification.svg?style=flat)](https://github.com/sagiegurari/simple-web-notification/blob/master/LICENSE) 4 | 5 | > Web Notifications made easy 6 | 7 | * [Overview](#overview) 8 | * [Demo](https://sagiegurari.github.io/simple-web-notification/) 9 | * [Usage](#usage) 10 | * [Installation](#installation) 11 | * [Limitations](#limitations) 12 | * [API Documentation](docs/api.md) 13 | * [Contributing](.github/CONTRIBUTING.md) 14 | * [Release History](#history) 15 | * [License](#license) 16 | 17 | 18 | ## Overview 19 | The simple-web-notification is a simplified web notifications API with automatic permissions support. 20 | 21 | This library requires no external dependencies, however the browser must support the Notification API or have a polyfill available. 22 | 23 | See [W3 Specification](https://dvcs.w3.org/hg/notifications/raw-file/tip/Overview.html) for more information. 24 | 25 | ## Demo 26 | [Live Demo](https://sagiegurari.github.io/simple-web-notification/) 27 | 28 | 29 | ## Usage 30 | In order to use the simplified web notification API you first must add the relevant dependencies: 31 | 32 | ```html 33 | 34 | ``` 35 | 36 | Now you can use the API anywhere in your application, for example: 37 | 38 | ```js 39 | document.querySelector('.some-button').addEventListener('click', function onClick() { 40 | webNotification.showNotification('Example Notification', { 41 | body: 'Notification Text...', 42 | icon: 'my-icon.ico', 43 | onClick: function onNotificationClicked() { 44 | console.log('Notification clicked.'); 45 | }, 46 | autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 47 | }, function onShow(error, hide) { 48 | if (error) { 49 | window.alert('Unable to show notification: ' + error.message); 50 | } else { 51 | console.log('Notification Shown.'); 52 | 53 | setTimeout(function hideNotification() { 54 | console.log('Hiding notification....'); 55 | hide(); //manually close the notification (you can skip this if you use the autoClose option) 56 | }, 5000); 57 | } 58 | }); 59 | }); 60 | ``` 61 | 62 | In case you wish to use service worker web notifications, you must provide the serviceWorkerRegistration in the options as follows: 63 | 64 | ```js 65 | navigator.serviceWorker.register('service-worker.js').then(function(registration) { 66 | document.querySelector('.some-button').addEventListener('click', function onClick() { 67 | webNotification.showNotification('Example Notification', { 68 | serviceWorkerRegistration: registration, 69 | body: 'Notification Text...', 70 | icon: 'my-icon.ico', 71 | actions: [ 72 | { 73 | action: 'Start', 74 | title: 'Start' 75 | }, 76 | { 77 | action: 'Stop', 78 | title: 'Stop' 79 | } 80 | ], 81 | autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 82 | }, function onShow(error, hide) { 83 | if (error) { 84 | window.alert('Unable to show notification: ' + error.message); 85 | } else { 86 | console.log('Notification Shown.'); 87 | 88 | setTimeout(function hideNotification() { 89 | console.log('Hiding notification....'); 90 | hide(); //manually close the notification (you can skip this if you use the autoClose option) 91 | }, 5000); 92 | } 93 | }); 94 | }); 95 | }); 96 | ``` 97 | 98 | In case you wish to invoke the permissions API manually you can use the webNotification.requestPermission function.
99 | This function triggers the request permissions dialog in case permissions were not already granted. 100 | 101 | ```js 102 | //manually ask for notification permissions (invoked automatically if needed and allowRequest=true) 103 | webNotification.requestPermission(function onRequest(granted) { 104 | if (granted) { 105 | console.log('Permission Granted.'); 106 | } else { 107 | console.log('Permission Not Granted.'); 108 | } 109 | }); 110 | ``` 111 | 112 | When using an AMD loader (such as RequireJS) or CommonJS type loader, the webNotification object is not automatically defined on the window scope. 113 | 114 | 115 | ## Installation 116 | Run npm install in your project as follows: 117 | 118 | ```sh 119 | npm install --save simple-web-notification 120 | ``` 121 | 122 | Or if you are using bower, you can install it as follows: 123 | 124 | ```sh 125 | bower install simple-web-notification --save 126 | ``` 127 | 128 | 129 | ## Limitations 130 | The web notifications API is not fully supported in all browsers. 131 | 132 | Please see [supported browser versions](http://caniuse.com/#feat=notifications) for more information on the official spec support. 133 | 134 | ## API Documentation 135 | See full docs at: [API Docs](docs/api.md) 136 | 137 | ## Contributing 138 | See [contributing guide](.github/CONTRIBUTING.md) 139 | 140 | 141 | ## Release History 142 | 143 | | Date | Version | Description | 144 | | ----------- | ------- | ----------- | 145 | | 2020-05-13 | v2.0.1 | Revert bower.json deletion but not use it in CI build | 146 | | 2020-05-11 | v2.0.0 | Migrate to github actions, upgrade minimal node version and remove bower | 147 | | 2019-02-08 | v1.0.32 | Maintenance | 148 | | 2018-06-25 | v1.0.28 | Expose webNotification.requestPermission #5 | 149 | | 2018-06-14 | v1.0.26 | Better error detection on chrome mobile #4 | 150 | | 2017-08-25 | v1.0.21 | Support service worker web notifications | 151 | | 2017-01-31 | v1.0.3 | Removed polyfill dependency | 152 | | 2017-01-22 | v1.0.0 | Official release | 153 | | 2017-01-22 | v0.0.2 | Initial release | 154 | 155 | 156 | ## License 157 | Developed by Sagie Gur-Ari and licensed under the Apache 2 open source license. 158 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "simple-web-notification", 3 | "version": "2.0.1", 4 | "description": "Web Notifications made easy.", 5 | "authors": [ 6 | "Sagie Gur-Ari " 7 | ], 8 | "license": "Apache-2.0", 9 | "homepage": "http://github.com/sagiegurari/simple-web-notification", 10 | "keywords": [ 11 | "notifications", 12 | "web notifications" 13 | ], 14 | "main": "web-notification.js", 15 | "ignore": [ 16 | "node_modules", 17 | "bower_components", 18 | ".github", 19 | "project", 20 | "test", 21 | "tests", 22 | "example", 23 | "target", 24 | ".travis.yml", 25 | ".atom.*.yml", 26 | "Gruntfile.js" 27 | ], 28 | "dependencies": {}, 29 | "devDependencies": {} 30 | } 31 | -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | | Date | Version | Description | 2 | | ----------- | ------- | ----------- | 3 | | 2020-05-13 | v2.0.1 | Revert bower.json deletion but not use it in CI build | 4 | | 2020-05-11 | v2.0.0 | Migrate to github actions, upgrade minimal node version and remove bower | 5 | | 2019-02-08 | v1.0.32 | Maintenance | 6 | | 2018-06-25 | v1.0.28 | Expose webNotification.requestPermission #5 | 7 | | 2018-06-14 | v1.0.26 | Better error detection on chrome mobile #4 | 8 | | 2017-08-25 | v1.0.21 | Support service worker web notifications | 9 | | 2017-01-31 | v1.0.3 | Removed polyfill dependency | 10 | | 2017-01-22 | v1.0.0 | Official release | 11 | | 2017-01-22 | v0.0.2 | Initial release | 12 | -------------------------------------------------------------------------------- /docs/api.md: -------------------------------------------------------------------------------- 1 | ## Objects 2 | 3 |
4 |
webNotification : object
5 |

A simplified web notification API.

6 |
7 |
8 | 9 | ## Typedefs 10 | 11 |
12 |
ShowNotificationCallback : function
13 |

'showNotification' callback.

14 |
15 |
PermissionsRequestCallback : function
16 |

'requestPermission' callback.

17 |
18 |
19 | 20 | 21 | 22 | ## webNotification : object 23 | A simplified web notification API. 24 | 25 | **Kind**: global namespace 26 | **Author**: Sagie Gur-Ari 27 | 28 | * [webNotification](#webNotification) : object 29 | * [.allowRequest](#webNotification.allowRequest) : Boolean 30 | * [.permissionGranted](#webNotification.permissionGranted) 31 | * [.requestPermission(callback)](#webNotification.requestPermission) 32 | * [.showNotification([title], [options], [callback])](#webNotification.showNotification) 33 | 34 | 35 | 36 | ### webNotification.allowRequest : Boolean 37 | True to enable automatic requesting of permissions if needed. 38 | 39 | **Access**: public 40 | 41 | 42 | ### webNotification.permissionGranted 43 | True if permission is granted, else false. 44 | 45 | **Access**: public 46 | 47 | 48 | ### webNotification.requestPermission(callback) 49 | Triggers the request permissions dialog in case permissions were not already granted. 50 | 51 | **Access**: public 52 | 53 | | Param | Type | Description | 54 | | --- | --- | --- | 55 | | callback | [PermissionsRequestCallback](#PermissionsRequestCallback) | Called with the permissions result (true enabled, false disabled) | 56 | 57 | **Example** 58 | ```js 59 | //manually ask for notification permissions (invoked automatically if needed and allowRequest=true) 60 | webNotification.requestPermission(function onRequest(granted) { 61 | if (granted) { 62 | console.log('Permission Granted.'); 63 | } else { 64 | console.log('Permission Not Granted.'); 65 | } 66 | }); 67 | ``` 68 | 69 | 70 | ### webNotification.showNotification([title], [options], [callback]) 71 | Shows the notification based on the provided input.
72 | The callback invoked will get an error object (in case of an error, null in 73 | case of no errors) and a 'hide' function which can be used to hide the notification. 74 | 75 | **Access**: public 76 | 77 | | Param | Type | Default | Description | 78 | | --- | --- | --- | --- | 79 | | [title] | String | | The notification title text (defaulted to empty string if null is provided) | 80 | | [options] | Object | | Holds the notification data (web notification API spec for more info) | 81 | | [options.icon] | String | /favicon.ico | The notification icon (defaults to the website favicon.ico) | 82 | | [options.autoClose] | Number | | Auto closes the notification after the provided amount of millies (0 or undefined for no auto close) | 83 | | [options.onClick] | function | | An optional onclick event handler | 84 | | [options.serviceWorkerRegistration] | Object | | Optional service worker registeration used to show the notification | 85 | | [callback] | [ShowNotificationCallback](#ShowNotificationCallback) | | Called after the show is handled. | 86 | 87 | **Example** 88 | ```js 89 | //show web notification when button is clicked 90 | document.querySelector('.some-button').addEventListener('click', function onClick() { 91 | webNotification.showNotification('Example Notification', { 92 | body: 'Notification Text...', 93 | icon: 'my-icon.ico', 94 | onClick: function onNotificationClicked() { 95 | console.log('Notification clicked.'); 96 | }, 97 | autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 98 | }, function onShow(error, hide) { 99 | if (error) { 100 | window.alert('Unable to show notification: ' + error.message); 101 | } else { 102 | console.log('Notification Shown.'); 103 | 104 | setTimeout(function hideNotification() { 105 | console.log('Hiding notification....'); 106 | hide(); //manually close the notification (you can skip this if you use the autoClose option) 107 | }, 5000); 108 | } 109 | }); 110 | }); 111 | 112 | //service worker example 113 | navigator.serviceWorker.register('service-worker.js').then(function(registration) { 114 | document.querySelector('.some-button').addEventListener('click', function onClick() { 115 | webNotification.showNotification('Example Notification', { 116 | serviceWorkerRegistration: registration, 117 | body: 'Notification Text...', 118 | icon: 'my-icon.ico', 119 | actions: [ 120 | { 121 | action: 'Start', 122 | title: 'Start' 123 | }, 124 | { 125 | action: 'Stop', 126 | title: 'Stop' 127 | } 128 | ], 129 | autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 130 | }, function onShow(error, hide) { 131 | if (error) { 132 | window.alert('Unable to show notification: ' + error.message); 133 | } else { 134 | console.log('Notification Shown.'); 135 | 136 | setTimeout(function hideNotification() { 137 | console.log('Hiding notification....'); 138 | hide(); //manually close the notification (you can skip this if you use the autoClose option) 139 | }, 5000); 140 | } 141 | }); 142 | }); 143 | }); 144 | ``` 145 | 146 | 147 | ## ShowNotificationCallback : function 148 | 'showNotification' callback. 149 | 150 | **Kind**: global typedef 151 | 152 | | Param | Type | Description | 153 | | --- | --- | --- | 154 | | [error] | error | The error object in case of any error | 155 | | [hide] | function | The hide notification function | 156 | 157 | 158 | 159 | ## PermissionsRequestCallback : function 160 | 'requestPermission' callback. 161 | 162 | **Kind**: global typedef 163 | 164 | | Param | Type | Description | 165 | | --- | --- | --- | 166 | | granted | Boolean | True if permission is granted, else false | 167 | 168 | -------------------------------------------------------------------------------- /docs/example/example.css: -------------------------------------------------------------------------------- 1 | .notification-form { 2 | padding: 10px; 3 | width: 60%; 4 | } 5 | -------------------------------------------------------------------------------- /docs/example/example.js: -------------------------------------------------------------------------------- 1 | /*global console: false */ 2 | 3 | document.addEventListener('DOMContentLoaded', function onLoad() { 4 | let serviceWorkerRegistration; 5 | 6 | if (navigator.serviceWorker) { 7 | navigator.serviceWorker.register('service-worker.js').then(function (registration) { 8 | serviceWorkerRegistration = registration; 9 | }); 10 | } 11 | 12 | const titleElement = document.getElementById('title'); 13 | const messageElement = document.getElementById('message'); 14 | const buttonElement = document.querySelector('.btn'); 15 | 16 | titleElement.value = 'Example Notification'; 17 | messageElement.value = 'This is some notification text.'; 18 | 19 | buttonElement.addEventListener('click', function onClick() { 20 | webNotification.showNotification(titleElement.value, { 21 | serviceWorkerRegistration: serviceWorkerRegistration, 22 | body: messageElement.value, 23 | onClick: function onNotificationClicked() { 24 | console.log('Notification clicked.'); 25 | }, 26 | autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 27 | }, function onShow(error, hide) { 28 | if (error) { 29 | window.alert('Unable to show notification: ' + error.message); 30 | } else { 31 | console.log('Notification Shown.'); 32 | 33 | setTimeout(function hideNotification() { 34 | console.log('Hiding notification....'); 35 | hide(); //manually close the notification (you can skip this if you use the autoClose option) 36 | }, 5000); 37 | } 38 | }); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Web Notification Example 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 | 17 | 18 |
19 |
20 | 21 | 22 |
23 | 24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /docs/service-worker.js: -------------------------------------------------------------------------------- 1 | 2 | self.addEventListener('install', function(event) {}); 3 | -------------------------------------------------------------------------------- /inch.json: -------------------------------------------------------------------------------- 1 | { 2 | "files": { 3 | "included": [ 4 | "*.js", 5 | "lib/**/*.js", 6 | "tasks/**/*.js" 7 | ], 8 | "excluded": [ 9 | "**/Gruntfile.js", 10 | "**/.eslintrc.js", 11 | "**/stylelint.config.js" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "simple-web-notification", 3 | "version": "2.0.1", 4 | "description": "Web Notifications made easy.", 5 | "author": { 6 | "name": "Sagie Gur-Ari", 7 | "email": "sagiegurari@gmail.com" 8 | }, 9 | "license": "Apache-2.0", 10 | "homepage": "http://github.com/sagiegurari/simple-web-notification", 11 | "repository": { 12 | "type": "git", 13 | "url": "http://github.com/sagiegurari/simple-web-notification.git" 14 | }, 15 | "bugs": { 16 | "url": "http://github.com/sagiegurari/simple-web-notification/issues" 17 | }, 18 | "keywords": [ 19 | "web", 20 | "notification" 21 | ], 22 | "main": "web-notification.js", 23 | "directories": { 24 | "test": "test/spec", 25 | "example": "example" 26 | }, 27 | "scripts": { 28 | "clean": "rm -Rf ./.nyc_output ./coverage", 29 | "format": "js-beautify --config ./.jsbeautifyrc --file ./*.js ./test/**/*.js", 30 | "lint-js": "eslint ./*.js ./test/**/*.js", 31 | "lint-css": "stylelint --allow-empty-input ./docs/**/*.css", 32 | "lint": "npm run lint-js && npm run lint-css", 33 | "jstest": "karma start --single-run", 34 | "docs": "jsdoc2md ./web-notification.js > ./docs/api.md", 35 | "test": "npm run clean && npm run format && npm run lint && npm run docs && npm run jstest", 36 | "postpublish": "git fetch && git pull" 37 | }, 38 | "devDependencies": { 39 | "chai": "^4", 40 | "eslint": "^8", 41 | "js-beautify": "^1", 42 | "jsdoc-to-markdown": "^8", 43 | "karma": "^6", 44 | "karma-chrome-launcher": "^3", 45 | "karma-coverage": "^2", 46 | "karma-mocha": "^2", 47 | "karma-sinon-chai": "^2", 48 | "mocha": "^10", 49 | "sinon": "^14", 50 | "sinon-chai": "^3", 51 | "stylelint": "^13", 52 | "stylelint-config-standard": "^22" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /test/helpers/notify-mock.js: -------------------------------------------------------------------------------- 1 | window.Notification = (function Notification() { 2 | 'use strict'; 3 | 4 | const noop = function () { 5 | return undefined; 6 | }; 7 | 8 | const permissionInfo = { 9 | value: null 10 | }; 11 | 12 | let oncePermission; 13 | 14 | const Lib = function (title, options) { 15 | const validateNotification = Lib.validateNotification || noop; 16 | validateNotification(title, options); 17 | 18 | const self = this; 19 | self.close = function () { 20 | if (options.onClick) { 21 | self.onclick(); 22 | } 23 | }; 24 | }; 25 | 26 | Lib.MOCK_NOTIFY = true; 27 | 28 | Object.defineProperty(Lib, 'permission', { 29 | enumerable: true, 30 | get() { 31 | return permissionInfo.value; 32 | } 33 | }); 34 | 35 | Lib.requestPermission = function (callback) { 36 | if (Lib.errorOnPermission) { 37 | setTimeout(function () { 38 | callback(new Error('test')); 39 | }, 5); 40 | } 41 | 42 | if (oncePermission) { 43 | oncePermission(); 44 | oncePermission = null; 45 | } 46 | 47 | setTimeout(callback, 5); 48 | }; 49 | 50 | Lib.setValidationNotification = function (validateNotification) { 51 | Lib.validateNotification = validateNotification || noop; 52 | }; 53 | 54 | Lib.setAllowed = function (validateNotification) { 55 | Lib.setValidationNotification(validateNotification); 56 | permissionInfo.value = 'granted'; 57 | }; 58 | 59 | Lib.setNotAllowed = function (validateNotification) { 60 | Lib.setValidationNotification(validateNotification); 61 | permissionInfo.value = 'not-granted'; 62 | }; 63 | 64 | Lib.onceRequestPermission = function (callback) { 65 | oncePermission = callback; 66 | }; 67 | 68 | return Lib; 69 | }()); 70 | -------------------------------------------------------------------------------- /test/spec/web-notification-spec.js: -------------------------------------------------------------------------------- 1 | /*global assert: false */ 2 | 3 | describe('simple-web-notification', function () { 4 | 'use strict'; 5 | 6 | const emptyValuesValidation = function (title, options) { 7 | assert.equal(title, ''); 8 | assert.deepEqual(options, { 9 | icon: '/favicon.ico' 10 | }); 11 | }; 12 | const validShowValidation = function (error, hide, done) { 13 | assert.isNull(error); 14 | assert.isFunction(hide); 15 | 16 | hide(); 17 | 18 | if (done) { 19 | done(); 20 | } 21 | }; 22 | const errorValidation = function (error, hide, done) { 23 | assert.isDefined(error); 24 | assert.isNull(hide); 25 | done(); 26 | }; 27 | 28 | beforeEach(function () { 29 | window.webNotification.allowRequest = true; 30 | }); 31 | 32 | describe('showNotification tests', function () { 33 | it('window', function () { 34 | assert.isObject(window.webNotification); 35 | assert.isFunction(window.webNotification.initWebNotificationFromContext); 36 | assert.isFunction(window.webNotification.showNotification); 37 | assert.isTrue(window.Notification.MOCK_NOTIFY); 38 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 39 | }); 40 | 41 | it('global', function () { 42 | const global = { 43 | Notification: window.Notification 44 | }; 45 | 46 | window.webNotification.initWebNotificationFromContext(global); 47 | 48 | assert.isObject(global.webNotification); 49 | assert.isFunction(global.webNotification.showNotification); 50 | }); 51 | 52 | it('define', function () { 53 | const global = { 54 | Notification: window.Notification 55 | }; 56 | 57 | window.define = function (factory) { 58 | const webNotification = factory(); 59 | 60 | assert.isObject(webNotification); 61 | assert.isFunction(webNotification.showNotification); 62 | 63 | delete window.define; 64 | }; 65 | window.define.amd = true; 66 | 67 | window.webNotification.initWebNotificationFromContext(global); 68 | }); 69 | 70 | it('module', function () { 71 | const global = { 72 | Notification: window.Notification 73 | }; 74 | 75 | window.module = { 76 | exports: {} 77 | }; 78 | 79 | window.webNotification.initWebNotificationFromContext(global); 80 | 81 | assert.isFunction(window.module.exports.showNotification); 82 | 83 | delete window.module; 84 | }); 85 | }); 86 | 87 | describe('requestPermission', function () { 88 | it('no callback', function () { 89 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 90 | window.Notification.errorOnPermission = true; 91 | 92 | window.webNotification.requestPermission(); 93 | 94 | window.Notification.errorOnPermission = false; 95 | }); 96 | 97 | it('callback not a function', function () { 98 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 99 | window.Notification.errorOnPermission = true; 100 | 101 | window.webNotification.requestPermission(true); 102 | 103 | window.Notification.errorOnPermission = false; 104 | }); 105 | 106 | it('allowed', function (done) { 107 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 108 | window.Notification.setAllowed(); 109 | 110 | window.webNotification.requestPermission(function (granted) { 111 | assert.isTrue(granted); 112 | done(); 113 | }); 114 | }); 115 | 116 | it('not allowed', function (done) { 117 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 118 | window.Notification.setNotAllowed(); 119 | 120 | window.webNotification.requestPermission(function (granted) { 121 | assert.isFalse(granted); 122 | done(); 123 | }); 124 | }); 125 | 126 | it('error', function (done) { 127 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 128 | window.Notification.errorOnPermission = true; 129 | 130 | window.webNotification.requestPermission(function (granted) { 131 | assert.isFalse(granted); 132 | done(); 133 | }); 134 | 135 | window.Notification.errorOnPermission = false; 136 | }); 137 | }); 138 | 139 | describe('showNotification', function () { 140 | describe('allowed', function () { 141 | it('all info', function (done) { 142 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 143 | window.Notification.setAllowed(function (title, options) { 144 | assert.equal(title, 'Example Notification'); 145 | assert.deepEqual(options, { 146 | body: 'Notification Text...', 147 | icon: 'my-icon.ico' 148 | }); 149 | }); 150 | 151 | window.webNotification.showNotification('Example Notification', { 152 | body: 'Notification Text...', 153 | icon: 'my-icon.ico' 154 | }, function onShow(error, hide) { 155 | validShowValidation(error, hide, done); 156 | }); 157 | }); 158 | 159 | it('auto close', function (done) { 160 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 161 | window.Notification.setAllowed(function (title, options) { 162 | assert.equal(title, 'Example Notification'); 163 | assert.deepEqual(options, { 164 | body: 'Notification Text...', 165 | icon: 'my-icon.ico', 166 | autoClose: 600 167 | }); 168 | }); 169 | 170 | window.webNotification.showNotification('Example Notification', { 171 | body: 'Notification Text...', 172 | icon: 'my-icon.ico', 173 | autoClose: 600 174 | }, function onShow(error, hide) { 175 | validShowValidation(error, hide, done); 176 | }); 177 | }); 178 | 179 | it('no params', function (done) { 180 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 181 | window.Notification.setAllowed(emptyValuesValidation); 182 | 183 | window.webNotification.showNotification(function onShow(error, hide) { 184 | validShowValidation(error, hide, done); 185 | }); 186 | }); 187 | 188 | it('no input', function () { 189 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 190 | window.Notification.setAllowed(emptyValuesValidation); 191 | 192 | window.webNotification.showNotification(); 193 | }); 194 | 195 | it('too many args', function (done) { 196 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 197 | window.Notification.setAllowed(emptyValuesValidation); 198 | 199 | window.webNotification.showNotification(1, 2, 3, 4, function () { 200 | assert.fail(); 201 | }); 202 | 203 | setTimeout(function () { 204 | done(); 205 | }, 50); 206 | }); 207 | 208 | it('null info', function (done) { 209 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 210 | window.Notification.setAllowed(emptyValuesValidation); 211 | 212 | window.webNotification.showNotification(null, null, function onShow(error, hide) { 213 | validShowValidation(error, hide, done); 214 | }); 215 | }); 216 | 217 | it('no callback', function (done) { 218 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 219 | window.Notification.setAllowed(function (title, options) { 220 | assert.equal(title, 'Example Notification'); 221 | assert.deepEqual(options, { 222 | body: 'Notification Text...', 223 | icon: 'my-icon.ico' 224 | }); 225 | }); 226 | 227 | window.webNotification.showNotification('Example Notification', { 228 | body: 'Notification Text...', 229 | icon: 'my-icon.ico' 230 | }); 231 | 232 | setTimeout(done, 50); 233 | }); 234 | 235 | it('no title', function (done) { 236 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 237 | window.Notification.setAllowed(function (title, options) { 238 | assert.equal(title, ''); 239 | assert.deepEqual(options, { 240 | body: 'no title', 241 | icon: '/favicon.ico' 242 | }); 243 | }); 244 | 245 | window.webNotification.showNotification({ 246 | body: 'no title' 247 | }, function onShow(error, hide) { 248 | validShowValidation(error, hide, done); 249 | }); 250 | }); 251 | 252 | it('with no icon', function (done) { 253 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 254 | window.Notification.setAllowed(function (title, options) { 255 | assert.equal(title, 'Example Notification'); 256 | assert.deepEqual(options, { 257 | body: 'Notification Text...', 258 | icon: '/favicon.ico' 259 | }); 260 | }); 261 | 262 | window.webNotification.showNotification('Example Notification', { 263 | body: 'Notification Text...' 264 | }, function onShow(error, hide) { 265 | validShowValidation(error, hide, done); 266 | }); 267 | }); 268 | 269 | it('no options', function (done) { 270 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 271 | window.Notification.setAllowed(function (title, options) { 272 | assert.equal(title, 'no options'); 273 | assert.deepEqual(options, { 274 | icon: '/favicon.ico' 275 | }); 276 | }); 277 | 278 | window.webNotification.showNotification('no options', function onShow(error, hide) { 279 | validShowValidation(error, hide, done); 280 | }); 281 | }); 282 | 283 | it('first time permissions', function (done) { 284 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 285 | window.Notification.setNotAllowed(function (title, options) { 286 | assert.equal(title, 'first time'); 287 | assert.deepEqual(options, { 288 | icon: '/favicon.ico' 289 | }); 290 | }); 291 | 292 | window.Notification.onceRequestPermission(function () { 293 | window.Notification.setAllowed(function (title, options) { 294 | assert.equal(title, 'first time'); 295 | assert.deepEqual(options, { 296 | icon: '/favicon.ico' 297 | }); 298 | }); 299 | }); 300 | 301 | window.webNotification.showNotification('first time', {}, function onShow(error, hide) { 302 | validShowValidation(error, hide, done); 303 | }); 304 | }); 305 | 306 | it('onClick', function (done) { 307 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 308 | window.Notification.setAllowed(function (title, options) { 309 | assert.equal(title, 'Example Notification'); 310 | assert.isFunction(options.onClick); 311 | }); 312 | 313 | window.webNotification.showNotification('Example Notification', { 314 | body: 'Notification Text...', 315 | icon: 'my-icon.ico', 316 | onClick() { 317 | done(); 318 | } 319 | }, function onShow(error, hide) { 320 | validShowValidation(error, hide); 321 | }); 322 | }); 323 | 324 | it('error on new', function (done) { 325 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 326 | const mockNotification = window.Notification; 327 | window.Notification = function () { 328 | throw new Error('test'); 329 | }; 330 | 331 | window.webNotification.showNotification('Example Notification', { 332 | body: 'Notification Text...', 333 | icon: 'my-icon.ico' 334 | }, function onShow(error, hide) { 335 | window.Notification = mockNotification; 336 | 337 | errorValidation(error, hide || null, done); 338 | }); 339 | }); 340 | 341 | it('serviceWorkerRegistration valid', function (done) { 342 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 343 | window.Notification.setAllowed(function (title, options) { 344 | assert.equal(title, 'Example Notification'); 345 | assert.equal(options.body, 'Notification Text...'); 346 | assert.equal(options.icon, 'my-icon.ico'); 347 | }); 348 | 349 | let tag; 350 | 351 | window.webNotification.showNotification('Example Notification', { 352 | body: 'Notification Text...', 353 | icon: 'my-icon.ico', 354 | serviceWorkerRegistration: { 355 | showNotification(title, options) { 356 | assert.equal(title, 'Example Notification'); 357 | assert.equal(options.body, 'Notification Text...'); 358 | assert.equal(options.icon, 'my-icon.ico'); 359 | assert.isDefined(options.tag); 360 | 361 | tag = options.tag; 362 | 363 | return { 364 | then(callback) { 365 | setTimeout(callback, 10); 366 | 367 | const output = {}; 368 | output.catch = function () { 369 | return undefined; 370 | }; 371 | 372 | return output; 373 | } 374 | }; 375 | }, 376 | getNotifications(options) { 377 | assert.equal(options.tag, tag); 378 | 379 | return { 380 | then(callback) { 381 | setTimeout(function () { 382 | callback([ 383 | { 384 | close() { 385 | return undefined; 386 | } 387 | } 388 | ]); 389 | }, 10); 390 | 391 | const output = {}; 392 | output.catch = function (errorCB) { 393 | assert.isFunction(errorCB); 394 | }; 395 | 396 | return output; 397 | } 398 | }; 399 | } 400 | } 401 | }, function onShow(error, hide) { 402 | validShowValidation(error, hide); 403 | 404 | done(); 405 | }); 406 | }); 407 | 408 | it('serviceWorkerRegistration with tag', function (done) { 409 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 410 | window.Notification.setAllowed(function (title, options) { 411 | assert.equal(title, 'Example Notification'); 412 | assert.equal(options.body, 'Notification Text...'); 413 | assert.equal(options.icon, 'my-icon.ico'); 414 | assert.equal(options.tag, '123'); 415 | }); 416 | 417 | window.webNotification.showNotification('Example Notification', { 418 | body: 'Notification Text...', 419 | icon: 'my-icon.ico', 420 | tag: '123', 421 | serviceWorkerRegistration: { 422 | showNotification(title, options) { 423 | assert.equal(title, 'Example Notification'); 424 | assert.equal(options.body, 'Notification Text...'); 425 | assert.equal(options.icon, 'my-icon.ico'); 426 | assert.equal(options.tag, '123'); 427 | 428 | return { 429 | then(callback) { 430 | setTimeout(callback, 10); 431 | 432 | const output = {}; 433 | output.catch = function () { 434 | return undefined; 435 | }; 436 | 437 | return output; 438 | } 439 | }; 440 | }, 441 | getNotifications(options) { 442 | assert.equal(options.tag, '123'); 443 | 444 | return { 445 | then(callback) { 446 | setTimeout(function () { 447 | callback([ 448 | { 449 | close() { 450 | return undefined; 451 | } 452 | } 453 | ]); 454 | }, 10); 455 | 456 | const output = {}; 457 | output.catch = function (errorCB) { 458 | assert.isFunction(errorCB); 459 | }; 460 | 461 | return output; 462 | } 463 | }; 464 | } 465 | } 466 | }, function onShow(error, hide) { 467 | validShowValidation(error, hide); 468 | 469 | done(); 470 | }); 471 | }); 472 | 473 | it('serviceWorkerRegistration no notifications', function (done) { 474 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 475 | window.Notification.setAllowed(function (title, options) { 476 | assert.equal(title, 'Example Notification'); 477 | assert.isDefined(options); 478 | }); 479 | 480 | window.webNotification.showNotification('Example Notification', { 481 | body: 'Notification Text...', 482 | serviceWorkerRegistration: { 483 | showNotification(title, options) { 484 | assert.equal(title, 'Example Notification'); 485 | assert.isDefined(options); 486 | 487 | return { 488 | then(callback) { 489 | setTimeout(callback, 10); 490 | 491 | const output = {}; 492 | output.catch = function () { 493 | return undefined; 494 | }; 495 | 496 | return output; 497 | } 498 | }; 499 | }, 500 | getNotifications(options) { 501 | assert.isDefined(options.tag); 502 | 503 | return { 504 | then(callback) { 505 | setTimeout(function () { 506 | callback([]); 507 | }, 10); 508 | 509 | const output = {}; 510 | output.catch = function (errorCB) { 511 | assert.isFunction(errorCB); 512 | }; 513 | 514 | return output; 515 | } 516 | }; 517 | } 518 | } 519 | }, function onShow(error, hide) { 520 | assert.isDefined(error); 521 | assert.isUndefined(hide); 522 | 523 | done(); 524 | }); 525 | }); 526 | 527 | it('serviceWorkerRegistration show catch', function (done) { 528 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 529 | window.Notification.setAllowed(function (title, options) { 530 | assert.equal(title, 'Example Notification'); 531 | assert.isDefined(options); 532 | }); 533 | 534 | window.webNotification.showNotification('Example Notification', { 535 | body: 'Notification Text...', 536 | serviceWorkerRegistration: { 537 | showNotification(title, options) { 538 | assert.equal(title, 'Example Notification'); 539 | assert.isDefined(options); 540 | 541 | return { 542 | then(validCB) { 543 | assert.isFunction(validCB); 544 | 545 | const output = {}; 546 | output.catch = function (errorCB) { 547 | setTimeout(function () { 548 | errorCB(new Error('test')); 549 | }, 10); 550 | }; 551 | 552 | return output; 553 | } 554 | }; 555 | } 556 | } 557 | }, function onShow(error, hide) { 558 | assert.isDefined(error); 559 | assert.equal(error.message, 'test'); 560 | assert.isUndefined(hide); 561 | 562 | done(); 563 | }); 564 | }); 565 | 566 | it('serviceWorkerRegistration get notifications catch', function (done) { 567 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 568 | window.Notification.setAllowed(function (title, options) { 569 | assert.equal(title, 'Example Notification'); 570 | assert.isDefined(options); 571 | }); 572 | 573 | window.webNotification.showNotification('Example Notification', { 574 | body: 'Notification Text...', 575 | serviceWorkerRegistration: { 576 | showNotification(title, options) { 577 | assert.equal(title, 'Example Notification'); 578 | assert.isDefined(options); 579 | 580 | return { 581 | then(callback) { 582 | setTimeout(callback, 10); 583 | 584 | const output = {}; 585 | output.catch = function () { 586 | return undefined; 587 | }; 588 | 589 | return output; 590 | } 591 | }; 592 | }, 593 | getNotifications(options) { 594 | assert.isDefined(options.tag); 595 | 596 | return { 597 | then(validCB) { 598 | assert.isFunction(validCB); 599 | 600 | const output = {}; 601 | output.catch = function (errorCB) { 602 | setTimeout(function () { 603 | errorCB(new Error('test')); 604 | }, 10); 605 | }; 606 | 607 | return output; 608 | } 609 | }; 610 | } 611 | } 612 | }, function onShow(error, hide) { 613 | assert.isDefined(error); 614 | assert.equal(error.message, 'test'); 615 | assert.isUndefined(hide); 616 | 617 | done(); 618 | }); 619 | }); 620 | }); 621 | 622 | describe('not allowed', function () { 623 | it('not allowed', function (done) { 624 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 625 | window.Notification.setNotAllowed(); 626 | 627 | window.webNotification.showNotification('not allowed', {}, function onShow(error, hide) { 628 | errorValidation(error, hide, done); 629 | }); 630 | }); 631 | 632 | it('not allowed to ask permissions', function (done) { 633 | assert.isTrue(window.webNotification.lib.MOCK_NOTIFY); 634 | window.Notification.setNotAllowed(); 635 | window.webNotification.allowRequest = false; 636 | 637 | window.webNotification.showNotification('no allowRequest', {}, function onShow(error, hide) { 638 | errorValidation(error, hide, done); 639 | }); 640 | }); 641 | }); 642 | }); 643 | }); 644 | -------------------------------------------------------------------------------- /web-notification.js: -------------------------------------------------------------------------------- 1 | /*global define: false */ 2 | 3 | /** 4 | * 'showNotification' callback. 5 | * 6 | * @callback ShowNotificationCallback 7 | * @param {error} [error] - The error object in case of any error 8 | * @param {function} [hide] - The hide notification function 9 | */ 10 | 11 | /** 12 | * 'requestPermission' callback. 13 | * 14 | * @callback PermissionsRequestCallback 15 | * @param {Boolean} granted - True if permission is granted, else false 16 | */ 17 | 18 | /** 19 | * A simplified web notification API. 20 | * 21 | * @name webNotification 22 | * @namespace webNotification 23 | * @author Sagie Gur-Ari 24 | */ 25 | 26 | /** 27 | * Initializes the web notification API. 28 | * 29 | * @function 30 | * @memberof! webNotification 31 | * @alias webNotification.initWebNotification 32 | * @private 33 | * @param {Object} global - The root context (window/global/...) 34 | * @param {function} factory - Returns a new instance of the API 35 | * @returns {Object} New instance of the API 36 | */ 37 | (function initWebNotification(global, factory) { 38 | 'use strict'; 39 | 40 | /*istanbul ignore next*/ 41 | const NotificationAPI = global.Notification || window.Notification; 42 | 43 | const webNotification = factory(NotificationAPI); 44 | 45 | /** 46 | * Initializes the web notification API (only used for testing). 47 | * 48 | * @function 49 | * @memberof! webNotification 50 | * @alias webNotification.initWebNotificationFromContext 51 | * @private 52 | * @param {Object} context - The root context (window/global/...) 53 | * @returns {Object} New instance of the API 54 | */ 55 | webNotification.initWebNotificationFromContext = function (context) { 56 | return initWebNotification(context, factory); 57 | }; 58 | 59 | if ((typeof define === 'function') && define.amd) { 60 | define(function defineLib() { 61 | return webNotification; 62 | }); 63 | } else if ((typeof module === 'object') && module.exports) { 64 | module.exports = webNotification; 65 | } else { 66 | global.webNotification = webNotification; 67 | } 68 | 69 | return webNotification; 70 | }(this, function initWebNotification(NotificationAPI) { 71 | 'use strict'; 72 | 73 | let tagCounter = 0; 74 | 75 | const webNotification = {}; 76 | 77 | /** 78 | * The internal Notification library used by this library. 79 | * 80 | * @memberof! webNotification 81 | * @alias webNotification.lib 82 | * @private 83 | */ 84 | webNotification.lib = NotificationAPI; 85 | 86 | /** 87 | * True to enable automatic requesting of permissions if needed. 88 | * 89 | * @member {Boolean} 90 | * @memberof! webNotification 91 | * @alias webNotification.allowRequest 92 | * @public 93 | */ 94 | webNotification.allowRequest = true; //true to enable automatic requesting of permissions if needed 95 | 96 | /*eslint-disable func-name-matching*/ 97 | Object.defineProperty(webNotification, 'permissionGranted', { 98 | /** 99 | * Returns the permission granted value. 100 | * 101 | * @function 102 | * @memberof! webNotification 103 | * @private 104 | * @returns {Boolean} True if permission is granted, else false 105 | */ 106 | get: function getPermission() { 107 | const permission = NotificationAPI.permission; 108 | 109 | /** 110 | * True if permission is granted, else false. 111 | * 112 | * @memberof! webNotification 113 | * @alias webNotification.permissionGranted 114 | * @public 115 | */ 116 | let permissionGranted = false; 117 | if (permission === 'granted') { 118 | permissionGranted = true; 119 | } 120 | 121 | return permissionGranted; 122 | } 123 | }); 124 | /*eslint-enable func-name-matching*/ 125 | 126 | /** 127 | * Empty function. 128 | * 129 | * @function 130 | * @memberof! webNotification 131 | * @alias webNotification.noop 132 | * @private 133 | * @returns {undefined} Undefined 134 | */ 135 | const noop = function () { 136 | return undefined; 137 | }; 138 | 139 | /** 140 | * Checks if web notifications are permitted. 141 | * 142 | * @function 143 | * @memberof! webNotification 144 | * @alias webNotification.isEnabled 145 | * @private 146 | * @returns {Boolean} True if allowed to show web notifications 147 | */ 148 | const isEnabled = function () { 149 | return webNotification.permissionGranted; 150 | }; 151 | 152 | /** 153 | * Displays the web notification and returning a 'hide' notification function. 154 | * 155 | * @function 156 | * @memberof! webNotification 157 | * @alias webNotification.createAndDisplayNotification 158 | * @private 159 | * @param {String} title - The notification title text (defaulted to empty string if null is provided) 160 | * @param {Object} options - Holds the notification data (web notification API spec for more info) 161 | * @param {String} [options.icon=/favicon.ico] - The notification icon (defaults to the website favicon.ico) 162 | * @param {Number} [options.autoClose] - Auto closes the notification after the provided amount of millies (0 or undefined for no auto close) 163 | * @param {function} [options.onClick] - An optional onclick event handler 164 | * @param {Object} [options.serviceWorkerRegistration] - Optional service worker registeration used to show the notification 165 | * @param {ShowNotificationCallback} callback - Invoked with either an error or the hide notification function 166 | */ 167 | const createAndDisplayNotification = function (title, options, callback) { 168 | let autoClose = 0; 169 | if (options.autoClose && (typeof options.autoClose === 'number')) { 170 | autoClose = options.autoClose; 171 | } 172 | 173 | //defaults the notification icon to the website favicon.ico 174 | if (!options.icon) { 175 | options.icon = '/favicon.ico'; 176 | } 177 | 178 | const onNotification = function (notification) { 179 | //add onclick handler 180 | if (options.onClick && notification) { 181 | notification.onclick = options.onClick; 182 | } 183 | 184 | const hideNotification = function () { 185 | notification.close(); 186 | }; 187 | 188 | if (autoClose) { 189 | setTimeout(hideNotification, autoClose); 190 | } 191 | 192 | callback(null, hideNotification); 193 | }; 194 | 195 | const serviceWorkerRegistration = options.serviceWorkerRegistration; 196 | if (serviceWorkerRegistration) { 197 | delete options.serviceWorkerRegistration; 198 | 199 | if (!options.tag) { 200 | tagCounter++; 201 | options.tag = 'webnotification-' + Date.now() + '-' + tagCounter; 202 | } 203 | const tag = options.tag; 204 | 205 | serviceWorkerRegistration.showNotification(title, options).then(function onCreate() { 206 | serviceWorkerRegistration.getNotifications({ 207 | tag 208 | }).then(function notificationsFetched(notifications) { 209 | if (notifications && notifications.length) { 210 | onNotification(notifications[0]); 211 | } else { 212 | callback(new Error('Unable to find notification.')); 213 | } 214 | }).catch(callback); 215 | }).catch(callback); 216 | } else { 217 | let instance; 218 | try { 219 | instance = new NotificationAPI(title, options); 220 | } catch (error) { 221 | callback(error); 222 | } 223 | 224 | //in case of no errors 225 | if (instance) { 226 | onNotification(instance); 227 | } 228 | } 229 | }; 230 | 231 | /** 232 | * Returns an object with the show notification input. 233 | * 234 | * @function 235 | * @memberof! webNotification 236 | * @alias webNotification.parseInput 237 | * @private 238 | * @param {Array} argumentsArray - An array of all arguments provided to the show notification function 239 | * @returns {Object} The parsed data 240 | */ 241 | const parseInput = function (argumentsArray) { 242 | //callback is always the last argument 243 | let callback = noop; 244 | if (argumentsArray.length && (typeof argumentsArray[argumentsArray.length - 1] === 'function')) { 245 | callback = argumentsArray.pop(); 246 | } 247 | 248 | let title = null; 249 | let options = null; 250 | if (argumentsArray.length === 2) { 251 | title = argumentsArray[0]; 252 | options = argumentsArray[1]; 253 | } else if (argumentsArray.length === 1) { 254 | const value = argumentsArray.pop(); 255 | if (typeof value === 'string') { 256 | title = value; 257 | options = {}; 258 | } else { 259 | title = ''; 260 | options = value; 261 | } 262 | } 263 | 264 | //set defaults 265 | title = title || ''; 266 | options = options || {}; 267 | 268 | return { 269 | callback, 270 | title, 271 | options 272 | }; 273 | }; 274 | 275 | /** 276 | * Triggers the request permissions dialog in case permissions were not already granted. 277 | * 278 | * @function 279 | * @memberof! webNotification 280 | * @alias webNotification.requestPermission 281 | * @public 282 | * @param {PermissionsRequestCallback} callback - Called with the permissions result (true enabled, false disabled) 283 | * @example 284 | * ```js 285 | * //manually ask for notification permissions (invoked automatically if needed and allowRequest=true) 286 | * webNotification.requestPermission(function onRequest(granted) { 287 | * if (granted) { 288 | * console.log('Permission Granted.'); 289 | * } else { 290 | * console.log('Permission Not Granted.'); 291 | * } 292 | * }); 293 | * ``` 294 | */ 295 | webNotification.requestPermission = function (callback) { 296 | if (callback && typeof callback === 'function') { 297 | if (isEnabled()) { 298 | callback(true); 299 | } else { 300 | NotificationAPI.requestPermission(function onRequestDone() { 301 | callback(isEnabled()); 302 | }); 303 | } 304 | } 305 | }; 306 | 307 | /** 308 | * Shows the notification based on the provided input.
309 | * The callback invoked will get an error object (in case of an error, null in 310 | * case of no errors) and a 'hide' function which can be used to hide the notification. 311 | * 312 | * @function 313 | * @memberof! webNotification 314 | * @alias webNotification.showNotification 315 | * @public 316 | * @param {String} [title] - The notification title text (defaulted to empty string if null is provided) 317 | * @param {Object} [options] - Holds the notification data (web notification API spec for more info) 318 | * @param {String} [options.icon=/favicon.ico] - The notification icon (defaults to the website favicon.ico) 319 | * @param {Number} [options.autoClose] - Auto closes the notification after the provided amount of millies (0 or undefined for no auto close) 320 | * @param {function} [options.onClick] - An optional onclick event handler 321 | * @param {Object} [options.serviceWorkerRegistration] - Optional service worker registeration used to show the notification 322 | * @param {ShowNotificationCallback} [callback] - Called after the show is handled. 323 | * @example 324 | * ```js 325 | * //show web notification when button is clicked 326 | * document.querySelector('.some-button').addEventListener('click', function onClick() { 327 | * webNotification.showNotification('Example Notification', { 328 | * body: 'Notification Text...', 329 | * icon: 'my-icon.ico', 330 | * onClick: function onNotificationClicked() { 331 | * console.log('Notification clicked.'); 332 | * }, 333 | * autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 334 | * }, function onShow(error, hide) { 335 | * if (error) { 336 | * window.alert('Unable to show notification: ' + error.message); 337 | * } else { 338 | * console.log('Notification Shown.'); 339 | * 340 | * setTimeout(function hideNotification() { 341 | * console.log('Hiding notification....'); 342 | * hide(); //manually close the notification (you can skip this if you use the autoClose option) 343 | * }, 5000); 344 | * } 345 | * }); 346 | * }); 347 | * 348 | * //service worker example 349 | * navigator.serviceWorker.register('service-worker.js').then(function(registration) { 350 | * document.querySelector('.some-button').addEventListener('click', function onClick() { 351 | * webNotification.showNotification('Example Notification', { 352 | * serviceWorkerRegistration: registration, 353 | * body: 'Notification Text...', 354 | * icon: 'my-icon.ico', 355 | * actions: [ 356 | * { 357 | * action: 'Start', 358 | * title: 'Start' 359 | * }, 360 | * { 361 | * action: 'Stop', 362 | * title: 'Stop' 363 | * } 364 | * ], 365 | * autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function) 366 | * }, function onShow(error, hide) { 367 | * if (error) { 368 | * window.alert('Unable to show notification: ' + error.message); 369 | * } else { 370 | * console.log('Notification Shown.'); 371 | * 372 | * setTimeout(function hideNotification() { 373 | * console.log('Hiding notification....'); 374 | * hide(); //manually close the notification (you can skip this if you use the autoClose option) 375 | * }, 5000); 376 | * } 377 | * }); 378 | * }); 379 | * }); 380 | * ``` 381 | */ 382 | webNotification.showNotification = function () { 383 | //convert to array to enable modifications 384 | const argumentsArray = Array.prototype.slice.call(arguments, 0); 385 | 386 | if ((argumentsArray.length >= 1) && (argumentsArray.length <= 3)) { 387 | const data = parseInput(argumentsArray); 388 | 389 | //get values 390 | const callback = data.callback; 391 | const title = data.title; 392 | const options = data.options; 393 | 394 | webNotification.requestPermission(function onRequestDone(granted) { 395 | if (granted) { 396 | createAndDisplayNotification(title, options, callback); 397 | } else { 398 | callback(new Error('Notifications are not enabled.'), null); 399 | } 400 | }); 401 | } 402 | }; 403 | 404 | return webNotification; 405 | })); 406 | --------------------------------------------------------------------------------