Google Chrome extension to close notification after user click - javascript

The Chrome extension works fine. My problem is that the notification closes in 7 seconds. I want for the user click to close the notification.
function engine(){
var latestId;
var ids;
var messages = [];
var newmessage = [];
$.get('http://localhost/site/json.php',function (data){
var json = $.parseJSON(data);
messages = json;
ids = json[0].id;
if(latestId == ids){
//no update
}else if(latestId === undefined){
var run = {
type: "basic",
title: "Title",
message: "Some message",
iconUrl : "icon.png",
};
chrome.notifications.create(run);
}
});
}

First create your notification and give it a notificationID parameter to close it later.
var notification = {
type:"basic",
title:"News From Us!",
message:"Google Chrome Updated to v50!",
iconUrl:"assets/images/icon.png"
};
chrome.notifications.create("notfyId",notification);
On notification click you can close notification using its id (which is "notfyId")
function forwardNotfy(){
chrome.notifications.clear("notfyId");
window.open(url); //optional
}
chrome.notifications.onClicked.addListener(forwardNotfy);
Now, when you click your notification it'll close.

This feature is currently only implemented in the beta channel, and not in the latest version of chrome. See here for details.
When it is implemented, you will be able to use requireInteraction : True like:
var run = {
type: "basic",
title: "Title",
message: "Some message",
iconUrl : "icon.png",
requireInteraction : True,
}
to implement this.

You can use notification.close();:
setTimeout(function() {
notification.close();
}, 2000);
Demo:
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: "Hey there! You've been notified!x",
});
notification.onclick = function () {
window.open("http://stackoverflow.com/a/13328397/1269037");
};
setTimeout(function() {
notification.close();
}, 2000);
}
}
<button onclick="notifyMe()">
Notify me!
</button>
JSBin Demo

notification.close() is used to close any notification.
For more information please see the below code-
To create the notification:
var notification = new Notification('OnlineOfferPrice', {
icon: 'icon.png',
body: "Test Message",
});
If you want to perform operation on notification click please use the below code. After your business logic it will automatically close-
notification.onclick = function () {
//write your business logic here.
notification.close();
};
If notification is not clicked and you want to close it automatically after 6 seconds-
setTimeout(function() { notification.close(); }, 6000);

Related

How do I add a URL to a notification when using the notification API?

I have created a simple notification in a standard index.html file by adding the following script to the bottom of the page. However, my goal is to add a URL to the notification, so that when the user clicks on the notification they are taken to a specific URL (window.open). I know this can be done as when searching for an answer on Google many sites have notifications that when clicked navigate to a different page or website. Nevertheless, I have not found a solution that I can get working. Any help welcome.
Notification.requestPermission();
Notification.requestPermission((permission) => {
switch (permission) {
case 'granted': {
console.log('Now we can send notifications!');
doNotify();
break;
}
case 'denied': {
console.log('User close the request pop-up!')
}
}
});
function doNotify(){
const title = "Test notification";
const img = "https://via.placeholder.com/600x400";
const text = Lorem ipsum;
const options = {
body: text,
icon: "https://via.placeholder.com/600x400",
data: {
},
vibrate: [200, 100, 200],
tag: "new-product",
image: img,
badge: "https://via.placeholder.com/128x128",
};
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
navigator.serviceWorker.ready.then(function(serviceWorker) {
serviceWorker.showNotification(title, options);
});
// setTimeout( n.close.bind(n), 9000); //close notification after 3 seconds
}
You missed a line that is very important for this to work. Define a notification with the Notification constructor in which you enter the title and options variables.
function doNotify() {
const title = "Test notification";
const img = "https://via.placeholder.com/600x400";
const text = "Lorem ipsum";
const options = {
body: text,
icon: "https://via.placeholder.com/600x400",
data: {},
vibrate: [200, 100, 200],
tag: "new-product",
image: img,
badge: "https://via.placeholder.com/128x128",
};
// Add this line.
const notification = new Notification(title, options);
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
navigator.serviceWorker.ready.then(function(serviceWorker) {
serviceWorker.showNotification(title, options);
});
}

Web Notification Display Duration

I am sending a notification web. I want to display up to ten minutes if the user does not click on the notification.
I used setTimeout, but it is displayed for about 15 seconds and then hidden.
please guide me.
This is my code:
function notify(title, message, link) {
var option = {
body: message,
dir: 'rtl',
title: title,
icon: '/Images/notification.png',
}
var notify = new Notification(title, option);
notify.onclick = function () {
window.open(link, '_blank');
notify.close();
};
notification.onshow = function () {
setTimeout(notification.close, 600000);
}
}
i have update your code. May this helps you !
var options = {
body: "My notification message",
dir : "ltr",
requireInteraction: true
};
var notify = new Notification('Hello User', options);
notify.onclick = function () {
notify.close();
};
notify.onshow = function () {
setTimeout(()=>{
notify.close();
}, 15000);
}
Just add the property requireInteraction.
var option = {
body: message,
dir: 'rtl',
title: title,
icon: '/Images/notification.png',
requireInteraction: true,
}
The requireInteraction read-only property of the Notification
interface returns a Boolean indicating that a notification should
remain active until the user clicks or dismisses it, rather than
closing automatically.
See here: https://developer.mozilla.org/en-US/docs/Web/API/notification/requireInteraction

Dialog cancel button needs to stop browser event

I am trying to display a dialog/confirm when a user browses away from a page/component.
I have the following dialog component which currently fires using a listener:
emptyBasket: function () {
basketChannel.publish({
channel: "basket",
topic: "emptyBasket",
data: {
}
});
},
OnClick which fires publish:
onTabLinkClick: function(e) {
var url = window.location.href;
var currentRoute = url.substr(url.length - 6)
if(this.state.BasketTotal > 0 && currentRoute != 'basket' ){
basketChannel.publish({
channel: "basket",
topic: "openDialog",
data: {
dialogTitle: 'Warning',
dialogContent: 'You have contacts in your basket, are you sure you want to leave?'
}
});
}
}
The listener in my dialog component then changes the state and displays the dialog:
_listenerForDialog: function(data) {
this.setState({
title: data.dialogTitle,
content: data.dialogContent,
visible:true
});
},
This works, but I would like to add an ok and cancel button, if the cancel button is clicked I would like stop the event.
How could I attach my component to e.preventDefault()?
Can I make this work like the native browser confirm()?
var confirmDialog = confirm("You have contacts in your basket, are you sure you want to leave?");
if(confirmDialog == false ){
e.preventDefault();
} else{
this.emptyBasket();
}
I am using the npm package https://www.npmjs.com/package/rc-dialog
UPDATED
onClose in current component:
onClose(){
this.setState({
visible:false
});
basketChannel.publish({
channel: "basket",
topic: "emptyBasket",
data: {
}
});
},
Thanks in advance

Using setInterval and JavaScript

I'm working with Notification API but i can't make it work with SetInterval(), can somebody point out what i'm doing wrong. As long as i click the event, the notification only displays once. Here is my code:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Web Notification is not supported');
return;
} else {
setInterval(Notification.requestPermission(function(permission) {
var notification = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
});
setTimeout(function() {
notification.close();
}, 2000);
}),5000);
}
;
});
});
I'm really stucked here, please halp.
You need to pass valid callback to setInterval(). Instead, you are passing the result of some method. Try this:
setInterval(function () {
Notification.requestPermission(function(permission) {
var notification = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
});
setTimeout(notification.close, 2000);
})}, 5000);
Bonus: see how I simplified your setTimeout callback, by just passing the notification.close method itself, instead of calling it in anonymous function. Much cleaner.
Wrap your method in anonymous function
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Web Notification is not supported');
return;
} else {
setInterval(function(){Notification.requestPermission(function(permission) {
var notification = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
});
setTimeout(function() {
notification.close();
}, 2000);
})},5000);
}
;
});
});
I found something like this :
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Web Notification is not supported');
return;
} else {
setInterval(notify, 5000);
}
});
function notify() {
Notification.requestPermission(function(permission) {
var n = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
})
setTimeout(function(){n.close()}, 2000)
})
}

Firefox Extension trouble using port.emit and port.on

I can't seem to get port.emit working correctly with my Firefox extension. From the init() function in popup.js the messages are correctly sent to main.js using addon.port.emit. Once they've been sent, the giveStorage message is correctly received in popup.js. However, this only works correctly when the original message is sent in the init function.
When I try sending the messages using using the jQuery change listener, the logs "Storage has been set." and "Sending storage to popup.js" come through, so popup.js is just not receiving it, but I have no idea why not. Only messages are logged correctly when ran from the init function.
If anyone has any ideas, or if you need any more information, please let me know and I'll see what I can do. Any help is greatly appreciated!
main.js
panel.port.on("setStorage", function (text) {
console.log("Storage has been set.");
ss.storage[text[0]] = text[1];
})
panel.port.on("getStorage", function (text) {
console.log("Sending storage to popup.js");
panel.port.emit("giveStorage", [text, ss.storage[text]])
})
popup.js
function init(){
$(".panel").hide();
addon.port.emit("getStorage", "username");
addon.port.emit("getStorage", "volume");
setInterval(function(){following();}, 60000);
}
addon.port.on("giveStorage", function (text) {
console.log("Message received from main.js");
if (text[1] !== null) {
if (text[0] === "username") {
username = text[1];
$('#menuFollowing').click();
}
else if (text[0] === "volume"){
volume = text[1];
$("#volume").val(volume);
$('#volumeValue').empty();
$('#volumeValue').append('Volume: ' + volume);
}
}
})
$('#volume').change(function(){
volume = $('#volume').val();
addon.port.emit("setStorage", ["volume", volume]);
addon.port.emit("getStorage", "volume");
});
Complete main.js
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var self = require("sdk/self");
var ss = require("sdk/simple-storage");
var notifications = require("sdk/notifications");
var panel = panels.Panel({
width: 500,
height: 500,
contentURL: self.data.url("popup.html"),
onHide: handleHide,
});
var button = ToggleButton({
id: "hitbox-plus",
label: "hitbox Plus",
icon: {
"16": "./icon16.png",
"48": "./icon48.png",
},
onChange: handleChange,
});
function handleChange(state) {
panel.contentURL = self.data.url("popup.html");
if (state.checked) {
panel.show({
position: button
});
}
}
function handleHide() {
button.state('window', {checked: false});
}
panel.port.on("getStorage", function (text) {
console.log("Sending storage to popup.js");
panel.port.emit("giveStorage", [text, ss.storage[text]])
})
panel.port.on("setStorage", function (text) {
console.log("Storage has been set.");
ss.storage[text[0]] = text[1];
})

Categories

Resources