Reputation: 101
Trying to build a chrome extension with notifications, and I would like a button that displays a notification. This is the HTML code:
<div><button onclick="notifyMe()">Notify me!</button></div>
This button shows in the extension, but when I press it, nothing happens. Here is my js code:
function notifyMe() {
var notification = new Notification("Hi there!");
}
Am I missing any js code? I have no idea
Upvotes: 0
Views: 1489
Reputation: 168
Your code is calling the Desktop Notification API and not the Chrome Notification API:
var notification = new Notification("Hi there!");
Apparently Google modified the level of permission in chrome extension (works perfectly in Chrome 43 +). Just include this line in your manifest.json, and Desktop notifications API will work (as well as the Chrome Notification API):
"permissions": [ "notifications", ...etc... ],
Adding notifications to the permissions scopes, you can check Notification.permission returns "granted".
Upvotes: 0
Reputation: 4876
Not sure if I'm following correctly but if you want to show a chrome notification there's actually the chrome notifications API
I'd do the following:
<div><button onclick="notifyMe()">Notify me!</button></div>
JS
function notifyMe() {
chrome.notifications.create('some id for this notification', {
type: 'basic', // "basic", "image", "list", or "progress"
title: 'a title for this notification',
message: 'the message you want to show'
}, function () { // called when the notification is created });
}
If you want to use the Notification
you have to ask for permissions first to use it (taken from the Web Notifications article on MDN):
// At first, let's check if we have permission for notification
// If not, let's ask for it
if (window.Notification && Notification.permission !== "granted") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
}
});
}
function notifyMe() {
if (window.Notification && Notification.permission === "granted") {
var n = new Notification("Hi!");
}
}
Upvotes: 1