You always want to update your users about new product lauch or exiting offerers. You can use mail notification or browser notification. There are many mail server provide to send emails to all users. There are many ways to send push notification in browser.
In this article, I will discuss about how to send push notifications using Push.js with a example. Here is the example how you can send push notification.
Installation:
Download Push.js using npm command.
npm install push.js --save
Or aleternatevily download package from Github.
Usage:
Include below script file before </body> tag. You will also need to include jQuery before script load.
<script src="push.js/bin/push.js"></script>
<script src="push.js/bin/serviceWorker.min.js"></script>
Example:
Send the push notification using any Javascript event. Here is the example for button click.
<!DOCTYPE html>
<html>
<body>
<button type="button">Send Notification</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="push.js/bin/push.js"></script>
<script src="push.js/bin/serviceWorker.min.js"></script>
<script type="text/javascript">
$('button').on('click', function() {
Push.create("Hello world!", {
body: "Its awesome day today!",
icon: '/logo.png',
timeout: 4000,
onClick: function () {
window.focus();
this.close();
}
});
});
</script>
</body>
</html>
If you want to close any notification before it automatically closes, you can use close() method.
<!DOCTYPE html>
<html>
<body>
<button class="open">Send Notification</button>
<button class="close">Close Notification</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="push.js/bin/push.js"></script>
<script src="push.js/bin/serviceWorker.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.open').on('click', function(){
Push.create("Hello world!", {
body: "Its awesome day today!",
icon: '/logo.png',
timeout: 4000,
tag: 'foo',
onClick: function () {
window.focus();
this.close();
}
});
});
$('.close').on('click', function() {
Push.close('foo');
});
});
</script>
</body>
</html>
I hope it will help you on your work.