chrome extension notification not showing - javascript

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

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!");
}
}

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".

Related

how can you overwrite or remove the signature "electron.app.Electron" from the desktop notification

I'm trying to remove or overwrite my notification signature made by electron.
here is what i get:
I am trying to whether overwrite the signature electron.app.Electron or remove it completely, by knowing
that I have tested it on test mode (npm run start), and also when packed as .exe
also I have noticed that I remove the icon the signature goes a way, but it is very unpleasant without one.
my current notification code is bellow:
function showNotification() {
const notification = new Notification("new message", {
body: "app launched",
icon: __dirname + '/icon.ico',
tag: 'soManyNotification',
hasReply: true
})
}
console.log(Notification.permission)
if (Notification.permission === "granted") {
showNotification()
//alert('we have permission');
} else if (Notification.permission === "denied") {
Notification.requestPermission()
};
any help would be gratefully appreciated ^^
// If this is running on Windows then set UserModelID for notification
if (isWin()) {
app.setAppUserModelId("Proper name to be replaced");
}

chrome notification doesn't display and return error

I got a problem with API notification with Chrome. It did not manage to display the notification and return an error into the console. I did not experience this problem with Firefox.
index.js
document.addEventListener('DOMContentLoaded', function () {
Notification.requestPermission(function (status) {
console.log('notification permission status: ', status);
displayNotification();
});
function displayNotification() {
if (Notification.permission === 'granted') {
navigator.serviceWorker.getRegistration()
.then(function (reg) {
var options = {
body: 'Buzz! Buzz!',
icon: '/static/img/logo_menu.png',
vibrate: [200, 100, 200, 100, 200, 100, 200],
tag: 'vibration-sample'
};
reg.showNotification('Hello world !', options);
})
}
}
}, false);
Error message
notification permission status: granted index.js:25
Uncaught (in promise) TypeError: Cannot read property 'showNotification' of undefined at index.js:25
Someone know why I experience this problem only on Chrome ?
Edit :
I didn't mention but I have a script tag :
<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
// Use the window load event to keep the page load performant
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js');
});
}
</script>
that root to sw.js file :
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');
if (workbox) {
console.log(`Yay! Workbox is loaded 🎉`);
} else {
console.log(`Boo! Workbox didn't load 😬`);
}
I solve the problem in addition to index.js setTimeout(). By this way, I'm waiting for that service worker working to start to read my file.

Chrome push notification - how to open URL adress after click?

I am new to Google Chrome Push notifications and I was just reading some questions and answers here, on stackoverflow and I have ended with this easy push notification javascript.
navigator.serviceWorker.register('sw.js');
function notify() {
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('test notification', {
body: 'Hey I am test!',
icon: 'image.png',
});
});
}
});
}
Its just simple notification, but I need open a new window with other webpage after click on notification.
I know it is possible, but I cant find examples using "serviceWorker" syntax.
Please help. Thanks.
I am guessing you are in a Service Worker context, because that's where Push Notifications are received. So you have the self object to add a event listener to, that will react to a click on the notification.
(Place this code in your sw.js file, which is your Service Worker script.)
self.addEventListener('notificationclick', function(event) {
let url = 'https://example.com/some-path/';
event.notification.close(); // Android needs explicit close.
event.waitUntil(
clients.matchAll({type: 'window'}).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
If you want to open website with dynamic URL received from FCM push notification or any other web push notification then
BELOW IS AN EXAMPLE OF SERVICE WORKER USED FOR FCM PUSH NOTIFICATION
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = payload.data.title; //or payload.notification or whatever your payload is
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
data: { url:payload.data.click_action }, //the url which we gonna use later
actions: [{action: "open_url", title: "Read Now"}]
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
and handle click event with below code
self.addEventListener('notificationclick', function(event) {
switch(event.action){
case 'open_url':
clients.openWindow(event.notification.data.url); //which we got from above
break;
case 'any_other_action':
clients.openWindow("https://www.example.com");
break;
}
}
, false);
Hope it helps!
(This code refers to firebase messaging) I was also searching for a soluting and the answer was very easy, but there was no doc saying it clearly. You need to put "click_action" = "your url" inside the notification json. Here is an example:
notification: {
title: "Come",
icon: '../../../../assets/logo.png',
vibrate: [300,100,400,100,400,100,400],
body: "some text",
click_action : "your link"
}
Hope it helps.
{
"notification": {
"title": "Hey there",
"body": "Subscribe to might ghost hack youtube channel",
"click_action" : "http://localhost:4200"
},
"to":"YOUR_TOKEN"
}
This worked for me
"#angular/fire": "^6.1.5",
"firebase": "^7.0 || ^8.0"

How to styling the HTML5 desktop Notification?

i try to make desktop notification for my web,
i found this guide usefull to make it with.
and successfully done it.
i post the code here too:
html:
<button id='button'>Notify me!</button>
js:
$('input[type=button]').click(notifyMe);
function notifyMe() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
var options = {
body: "This is the body of the notification",
icon: "icon.jpg",
dir: "ltr"
};
var notification = new Notification("Hi there", options);
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function(permission) {
if (!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === "granted") {
var options = {
body: "This is the body of the notification",
icon: "icon.jpg",
dir: "ltr"
};
var notification = new Notification("Hi there", options);
}
});
}
}
Demo
my question is, there is a way to change the default style of it?
I'm afraid it's not possible to edit more than what you're doing. like alert elements, it's the browser who format the notifications.

Display Notification When New Page Load in chrome extensions

I am developing an extension in google chrome.I want to show desktop notification when any new page loads in currently active tab.
But my written code is not working properly.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
if (changeInfo.status === 'complete') {
chrome.tabs.executeScript(tabId, {
chrome.notifications.create(‘id1’, {
type: ‘basic’,
iconUrl: ‘icon.png’,
title: ‘Review Baed Surfing’,
message: ‘Check URL now by clicking FAKE URL icon infront on Address Bar!’,
priority: 0
},
function() { /* Error checking goes here */}
);
});
}
});
I think you only need to call chrome.notifications.create() in background script and chrome.tabs.executeScript only accept file url or code (css, js) to inject.
And you could check the following items when the notification doesn't show as expected:
Add "notification" to permissions in manifest.json.
"permissions": ["notifications"]
Notifications API only supports Windows, Chrome OS and Mac currently.
The 'option' parameter of create function must include a notification title, message and iconUrl. The rich notification will not work properly without any error if you missed any one of them.
var opt = {
type: "basic",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "url_to_small_icon"
}
Hope this is helpful.
[SOLVED]
i make following changes in code
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
chrome.notifications.create('id1',{
type: 'basic',
iconUrl: 'icon.png',
title: 'Review Baed Surfing',
message: 'Check URL now by clicking FAKE URL icon infront on Address Bar!',
priority: 0
},
function() { /* Error checking goes here */}
);
}
});
Now it works properly.
Thank You,

Categories