Chome push notifications disappearing after a couple seconds - google-chrome

I am building a system to send web push notifications with chrome. When someone receives my push notification on their desktop PC they see the notification for about 10 seconds. If they don't click on the notification it will then disappear after about 10 seconds.
I see other websites sending push notifications that do not disappear. I believe there is some setting I am not using to make my messages stay on the screen until clicked or exited. Does anyone know this setting or parameter?

It looks like you need to use the 'requireInteraction' option creating the notification in your service worker. Just set it to 'true' to say the browser you need the user interaction. Here is how you do this.
...in your service worker script when you create a notification:
self.addEventListener('push', function(e) {
var notification = self.registration.showNotification(
"Hi! Click me!",
{
requireInteraction: true,
body: "I'm not going to disappear"
}
);
e.waitUntil(notification);
});
Also don't forget to close it on click event:
...later in the service worker script:
self.addEventListener('notificationclick', function(e) {
e.preventDefault();
e.notification.close();
// Do click actions
});
Browser comparability: unfortunately not everybody supports this option yet: Firefox doesn't. See the Mozilla reference for details: https://developer.mozilla.org/en-US/docs/Web/API/notification/requireInteraction
But it works fine in Chrome.

You may want to try the suggested solution in this SO post which consists the following steps:
Register listeners for all the events mentioned in chrome.notifications.
Register a timeout after a few seconds (e.g. 30) -after the notification is hidden- that will delete and re-create the notification (so it effectively stays visible on the screen.
If any of the listeners set on step 1 fires, it means the user interracted with the notification, so cancel the timeout (you don't need to re-create the notification).
See the post for more information.

Related

Google Chrome - add to homescreen - force refresh

I have a website with "add to homescreen" enabled - i.e. I have got a manifest.json file with "display": "standalone".
The problem I'm having is when I open the website via the homescreen shortcut, it will resume from when I last accessed it. I have to pull to refresh to make it fetch the latest content.
My question is, is it possible to make it do a refresh every time it is accessed?
If you'd like to take specific action inside of your web app whenever it moves from the "background" to the "foreground" again, you could listen for the appropriate events using the Page Lifecycle API.
The most straightforward way of doing this would probably be to listen for visibilitychange events, and programmatically refresh your data source when you detect that the current visibilityState has transitioned to 'visible'.
This could look like:
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
// Your refresh logic goes here.
}
});

How to set a closing time for notification extension chrome

I'm developing an extension with chrome.notifications would like to set a time for closing the notification, how can I do this?
Chrome automatically hides the notification. How long it stays on screen depends on the priority attribute. Note that everywhere except Chrome OS the hidden notification is effectively closed, as the Notification Center was removed.
It's possible to keep the notification shown, but you'll have to resort to dirty tricks. If you don't want to do it the hard way, consider using Web Notifications instead - they will not be hidden.
Update: Both chrome.notifications and Web Notifications APIs now implement a boolean flag requireInteraction that defines whether Chrome will fade the notification away automatically or not.
You can still manually close (i.e., remove completely) the notification by calling chrome.notifications.clear() with the notification ID.
To schedule something, you can either use DOM intervals, or chrome.alarms API.
I'm using this in my project
var opt = {type, title, message, etc....}
chrome.notifications.create("", opt, function(id) {
timer = setTimeout(function(){chrome.notifications.clear(id);}, 2000);
});
notification is closed after 2 sec (2000 ms)

Google Cloud Messaging for Chrome - a received message is not shown as a popup

I downloaded Google push-sample-app code, removed the key from the manifest, uploaded the app to the Chrome Web Store, then installed it in Chrome from the Web Store.
Now chrome://extensions/ lists the app as "Enabled", with "Inspect views: background page (Inactive)".
Chrome Task Manager doesn't list the app as currently running.
If at chrome://extensions/ tab, I click "background page (Inactive)" link for "Push Messaging Sample" app, then an inspect view shows up in a separate Chrome window, and a new entry appears in the Chrome Task Manager: "Background Page: Push Messaging Sample". As long as an inspect view Chrome window is open, an event page "background.js" doesn't get offloaded. And When a message is sent to the push messaging service, a popup window with the message text appears.
If I close the inspect view Chrome window, and send a message to the push messaging service, Chrome Task Manager shows that an event page "background.js" gets loaded, then offloaded in a few seconds disappearing from the Task manager. However, a popup window with a message does not appear.
How this app needs to be changed to show popup messages without any extra Chrome windows running?
The sample app does not show notification from "background page is inactive" state because when the background page is woken up, the event handler for chrome.pushMessaging.onMessage is not set up.
When user launches the app by clicking on its icon, the chrome.app.runtime.onLaunched() event is fired. But when background page is activated because of some incoming event (like push messaging or alarm), the onLaunched is not fired - instead, only the 'initial script', the JS code outside of functions, is executed. The initial script of background page must register event listeners so after initial load Chrome knows which handler to call. The sample app only registers the onMessage handler in onLaunched, but not from initial script.
It is easy to 'fix' the sample app - just move the call of setupPush() from onLaunched() handler to the very end of background.js file:
background.js:
....
// When a Push Message arrives, show it as a text notification (toast)
function showPushMessage(payload, subChannel) {
var notification = window.webkitNotifications.createNotification(
'icon.png', 'Push Message',
"Push message for you! " +
payload +" [" + subChannel + "]");
notification.show();
}
setupPush(); // <-- this executes every time page loads, not only in onLaunched
This will cause setupPush() to be executed every time background page is activated, whether user launched the app or the app is started in background in response to incoming push message.
This question / answer explained what is missing:
"Because the listeners themselves only exist in the context of the event page, you must use addListener each time the event page loads; only doing so at runtime.onInstalled by itself is insufficient."
To fix push-sample-app, all is needed is to add to background.js:
// Register with the Push Messaging system for the Push Message.
chrome.pushMessaging.onMessage.addListener(messageCallback);

How to stop chrome tab focus?

I am writing a chrome extension which refreshes pages after a certain time interval. I got it working fine, but a new problem occurred..
Whenever the page refreshes the tab gets highlighted (starts blinking) or else comes in focus. Ie it is getting focused on.
Now this works differently depending on the chrome browser state, but the core issue is the same:
1. If user switches tab to another one (suppose writing an email in gmail.com) while waiting for page to refresh itself, on refresh the current mail tab will get outfocused (so he wont be able to continue writing his email without clicking on the window first)
If the user swithces to any other application on his workspace (like my computer, outlook etc), on refresh the chrome icon will start blinking on the taskbar (highly annoying)
If the user has multiple chrome windows open with a tab each running the refresh code, then on refresh that window will get focus (come at top). This will repeat for all chrome windows whenever there specific refreshes occur.
Steps to reproduce the problem:
Write a simple extension
In the background page, create a new tab with:
chrome.tabs.create({ url: "https://drive.google.com/", active: false})
Now in a loop, after every minute, refresh this tab with:
chrome.tabs.update(tab_id, {url: "https://drive.google.com/",
active: false,
highlighted: false});
Once you start this code, either minimize the chrome window or shift your workspace and focus on something else.
Every time tabs.update() gets called, the Chrome window either unminimizes from task bar, or gets the focus on it.
What i want is to remove this focus whenever the page refreshes.
If anyone can please help me with this i would be very greatful.
Thanks,
Umair
EDIT:
code for my background.js file
chrome.webNavigation.onErrorOccurred.addListener(function (_errorDetails) {
var myUrl = 'myPage.htm';
chrome.tabs.update(_errorDetails.tabId, { url: myUrl, active: false,
highlighted: false, selected: false },
function (_tabDetails) {
chrome.windows.update(_tabDetails.windowId, { drawAttention: false });
});
});
Iv tried to make all related parameters false to stop focus.
Also on myPage.htm the function reload() is called on pageload.
function reloadPage() {
//code for 10 second delay
location.reload();
}
myPage.htm is itself a simple page showing few lines of text like 'Unable to load page' etc.
I changed the code and got it working for me as per my requirements.
What i did was instead of using the reload function to refresh page, i used the message passing technique of the chrome extension to send a message (containing url and tabID) from my js to background.js and update the relevant tab there with the url.
I know this is not a perfect solution, but it worked for me, therefore im sharing it.

How to prevent reload of pages in Chrome Extension?

I have written a Chrome Extension to Clear TYPO3 CMS Caches right out of the browser's address bar.
Now I would like to add an optional feature, to clear the caches automatically on page refresh . That means, when the user presses F5, CTRL+R, clicks the reload icon in toolbar or clicks in context menu to "Reload", first my ajax script should be executed (to clear the CMS cache) and after it, the page may get reloaded.
Is there a possibility to do it with the Chrome API?
I tried first the window.onbeforeupdate event in content script - and this is triggered always when the page is reloading, but also if I close the window or switch to another website. And furthermore I can't tell the browser to wait for my ajax request here.
What works is to check in document.onkeydown event the keys 116 (F5) and 82 (R) with control key and use event.preventDefault(). But this will not cover the two other possible cases to refresh the cache.
Thanks!
I've found a solution. It does not really match my requirements, but it works (even better).
Chrome provides a webRequest API which allows you to modify or block all http requests.
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
if (!severalConditionsToCheckIfIWantToDoTheMagic) {
return;
}
$.ajax(url, {
async:false,
complete:function () {
return {redirectUrl:details.url};
}
});
},
{urls:["<all_urls>"]},
["blocking"]
);
In this example first I check if I want to do the ajax request. If yes, the next step is no do the ajax request. It is important, that the request is not asynchronous. On complete I return the original url of the request, which is basically just a reload.
The reason why it does not really match my requirements, is that it will be triggered always, on any request, not just on reload. That means in my conditions I have to check against:
Other websites
Other request types (loading css, js or images are also request), I just need the type 'main_frame'
Some variables belonging to my extension
Now, the script will be also triggered when I click on a link which is on the website - but for my case this is fine.