Detect notification popup using JavaScript - javascript

I am creating userscript for messenger site I use. Is it possible to detect when site create notification pop up(usually on right bottom of screen) and get content of notification?
document.addEventListener('???', function(e) { // when I get notification popup(get message)
// and get content of notification
});

In websites I believe there's a Notifications API in which you can check here:
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API
It has all functions to request permissions, detect & listen to notifications on in websites. For example:
btn.addEventListener('click', function() {
let promise = Notification.requestPermission();
// wait for permission
})

Related

Browser service worker - Unchecked runtime.lastError: listener indicated an asynchronous response by returning true but the message channel closed

I am creating a push notification system for browsers.
What works...
If the corresponding website is loaded in the browser and if the browser is in the BACKGROUND the service worker correctly receives the information and pops up the message in the system tray. On clicking a button in that message, it brings the browser window back to focus and performs the action I want.
What doesn't work...
If the browser is closed OR the browser is open but the website is not loaded in any of the tabs, the service worker correctly receives the information and pops up the message in the system tray. However on clicking a button in that message, nothing happens :(
I tried to debug by closing the browser, sending the message, on receipt of message in system tray I manually loaded up the browser to the website and view console debug. When I then click the button in system try message nothing happened but I received the following message in the browser:
service worker message Unchecked runtime.lastError: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
Could anyone give me any pointers. I've enclosed below the portion of service worker code that is called when a button on the system tray message is clicked...
//If a browser window is in background, and the domain of this project is loaded in to it,
//we force that window back in to the foreground (and re-display the message in the browser again via the postMessage function)
//However this isn't working if browser is closed at point of system tray message receipt...
function returnWindowToForeground(event,_action) {
event.waitUntil(
clients.matchAll(
{ type: 'window', includeUncontrolled: true }
)
.then(
(clientList) => {
var windowWithDomain = clientList.some((windowClient) => {
var found = -1;
let url = windowClient.url;
if( websiteurl == url.slice(0, websiteurl.length) ) {
found = i;
windowClient.focus(); //Go back to website in browser
windowClient.postMessage([currpayload,_action]); //Post message to browser window
}
return found;
});
//If not found, spawn a new browser tab, load url and post message
if (windowWithDomain== -1 && clients.openWindow)
{
clients.openWindow(websiteurl)
.then((windowClient) => (windowClient) ? windowClient.postMessage([currpayload,_action]) : null;
}
)
);
}
Thanks for your help, sorry it's a bit long.

Trying to enable sound on incoming SMS in Flex Twilio

I've set up a workspace in Flex to handle incoming SMS contacts from customers. What I'm trying to do is enable an audio notification that a new SMS message has come into Flex. I'm working on a Flex Plugin to do this.
What I've done is added a listener for a new reservation being created.
If a new reservation has been created I'm trying to play an audio file as the notification. I've enabled error logging but the code is not triggering any errors.
init(flex, manager) {
let ringer = new Audio("*.mp3");
ringer.loop = true;
const resStatus = ["accepted","rejected","rescinded","timeout"];
manager.workerClient.on("reservationCreated", function(reservation) {
if (reservation.task.taskChannelUniqueName === 'sms') {
ringer.play()
};
resStatus.forEach((e) => {
reservation.on(e, () => {
ringer.pause()'''
I was expecting the mp3 to play if a new reservation was created with a taskchanneldefinition name of sms. New sms messages come into the sms channel. When running on Flex, no sound plays and no errors are being logged.
try playing sounds outside this method, does it work?
a few possible problems that you may face:
1) new Audio("*.mp3"), do you load a sound here properly? i think something is wrong with this one
if not
2) you likely need to interact with flex-ui as said herehttps://www.twilio.com/docs/flex/audio-player#troubleshooting
here is an example that i have and it works:
manager.chatClient.on("messageAdded", () => {
//some stuff going on here
new Audio(NEW_MESSAGE_AUDIO).play();
});
where NEW_MESSAGE_AUDIO is a data:audio/mpeg;base64 file

Adding mobile web app to home screen using button

I'm trying to add app to home screen via button located in "settings" page of my HTML5 mobile web app (Notice: It is working if I'm trying to add it via Chrome menu).
I've set up all of these steps:
The PWA must not already be installed
Web app must include a web app manifest.
Web app must be served over a secure HTTPS connection.
Web app has registered a service worker with a fetch event handler.
Currently I'm debugging it via Chrome Dev tools and listening to beforeinstallprompt with that code from official docs.
<script>
let deferredPrompt;
window.addEventListener('beforeinstallprompt', function(event) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
});
// Installation must be done by a user gesture! Here, the button click
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
</script>
How to catch event on /home page, and pass it to /settings page so I could fire the event via (onClick) event?
Currently I'm using:
Angular CLI: 6.1.4
Node: 8.11.4
OS: win32 x64
Save it to global (window) object (or somewhere else with global access) and on /settings page in event handler call window.deferredPrompt.prompt()?

My JavaScript code stop running when the mobile screen is locked?

Here is my code:
firebase.initializeApp(config);
if(!window.Notification){
alert('Not supported');
}else{
Notification.requestPermission().then(function(p){
if(p=='denied'){
alert('You denied to show notification');
}else if(p=='granted'){
alert('You allowed to show notification');
}
});
}
var database = firebase.database().ref("sensor/Motion");
database.on('child_added', function() {
$("#Mt").val("Motion detected");
$("#dateM").val( moment().format('LLL') );
if(Notification.permission!=='default'){
var notification = new Notification('Alert', {
icon: 'alert-icon-red.png',
body: "Motion detected!",
});
}else{
alert('Please allow the notification first');
}
Everything works fine in my desktop browser but on my Android device, when the screen is locked, it works for a few minute and after that it doesn't work. I get no notifications.
It sounds like your mobile browser is stopping tasks when the screen is locked, likely to improve battery life. That in general sounds like a good thing.
If you want to alert the user of an event that happens when they're not using their device, consider using Firebase Cloud Messaging for sending and handling those messages. This ensures it uses a communication channel that is more likely to be active when the user is not actively using the app.

Limit cache length of chrome notifications when Windows is locked

Is there any sort of option in the Web API Notifications to allow a notification to not be displayed while the PC is locked?
I have setup a web application that displays Notifications when certain events happen. This is something I use at work to monitor different things so I leave it open nearly 24/7. Problem is that when the PC is locked, the notifications are saved until I unlock the PC. Then I get flooded with all the notifications that were triggered while the PC was locked.
I cannot use an sort of idle page script to only show notifications if the page was used or interacted with in the last X number of minutes because I don't actually want to have to look at the page to still allow the notifications.
// set title and message body
var title = 'Test message';
var message 'This is a test message that should only show when logged into the PC';
// setup some options
var options = {
// someOptionToDisableLockedNotificationsOnWindows?
body: message,
icon: 'assets/yukon_logo_small.png',
};
// create the notification using the above settings
var notification = new Notification( title, options );
// focus tab and close the notification on click
notification.addEventListener('click', function(e) {
window.focus();
e.target.close();
}, false);
I have tried to randomly set some options, don't remember them all but they didn't do anything or broke my code.
I was not able to find anything in the API:
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API

Categories