How to styling the HTML5 desktop Notification? - javascript

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.

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

How to activate user location sharing once user has declined location sharing using react?

I want to display the native browser popup for location sharing even after user denying the location sharing.
consider the scenario,
user clicks location sharing button, native browser popup is shown. he allows to share his location the location button turns to green.
if the user declines sharing location, location button should be grey. and clicking that button should show a native browser popup...
with the code below, I am able to display a native popup browser again if I clear the site data from developertools->application->clear site data.
is it possible to show the native browser popup with clearing site data or so?
below is the code,
class Location extends react.purecomponent {
state = {
active: false,
};
componentDidMount() {
if (navigator.geolocation) {
navigator.permissions.query({name:
'geolocation'}).then((result) =>
{
if (result.state === 'granted') {
this.setState({active: true});
} else if (result.state === 'denied') {
this.setState({active: false});
}
});
}
}
handle_location_btn_click = () => {
if (navigator.geolocation) {
navigator.permissions.query({name:'geolocation'})
.then((result) => {
if (result.state === 'granted') {
this.setState({active: true});
} else if (result.state === 'prompt') {
navigator.geolocation
.getCurrentPosition(this.use_position, null);
} else if (result.state === 'denied') {
this.setState({location_active: false});
}
});
} else {
console.log("geolocation unavailable");
}
};
render = () => {
return (
<button type="button" className={this.active ? ' active':
'')}
onClick={this.handle_location_btn_click}>
</button>
);
};
}
Could someone help me with this.thanks
No, it is not possible once the user said no to a location on specific domain

How to use javascript click to trigger POST

When a user clicks...
<%= content_tag(:button, "Send", class: "webpush-button") %>
# Previous Attempt: <%= button_to 'send', class: "webpush-button" %>
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post("/post", {
subscription: subscription.toJSON(),
message: 'You clicked a button!'
});
});
});
});
</script>
he should be taken through...
class PushNotificationsController < ApplicationController
def push
Webpush.payload_send(
message: params[:message],
endpoint: params[:subscription][:endpoint],
p256dh: params[:subscription][:keys][:p256dh],
auth: params[:subscription][:keys][:auth],
vapid: {
subject: "mailto:sender#example.com",
public_key: ENV['VAPID_PUBLIC_KEY'],
private_key: ENV['VAPID_PRIVATE_KEY']
}
)
end
end
but instead nothing happens. The .webpush-button javascript never kicks in. I put it in two places and it still has no effect...
application.js
/ Register the serviceWorker script at /serviceworker.js from our server if supported
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js').then(function(reg) {
console.log('Service worker change, registered the service worker');
});
}
// Otherwise, no push notifications :(
else {
console.error('Service worker is not supported in this browser');
}
// When serviceWorker is supported, installed, and activated,
// subscribe the pushManager property with the vapidPublicKey
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: window.vapidPublicKey
});
});
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: 'You clicked a button!'
});
});
});
});
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
console.error("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
console.log("Permission to receive notifications has been granted");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
console.log("Permission to receive notifications has been granted");
}
});
}
application.html.erb
<script>
window.vapidPublicKey = new Uint8Array("<%= #decodedVapidPublicKey %>");
</script>
Now based on the tutorial and git code I used... the subscription should be gathered from the serviceworker so then why am I still getting a nil error?
I'm using serviceworker & webpush gems and followed this VAPID tutorial.
Not a duplicate. The other question is focused on params. This one is focused on javascript not triggering.
First, you should only put the javascript at one place.
Second, add the .webpush-button click method after page be ready
$(document).on('ready page:load', function () {
});
And in the chrome dev tools, Tab Event Listeners, check if the html element has click event.

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"

chrome extension notification not showing

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

Categories