How do I create desktop notifications in Chrome extensions?

3

How to create Desktop notifications to use in web-extensions (Firefox, Chrome and etc.) and also would like to know if there is any difference between Chrome, Opera and Firefox?

  

Note: This is a tutorial question, read more at:

     
    
asked by anonymous 03.01.2018 / 21:26

1 answer

4
  

Is there a difference between Chrome, Opera and Firefox?

Currently there are some differences, but they are very specific, in this case I will cite only about the chrome. object, in Firefox it is supported, however its default is the browser. object and then maybe in the future chrome. can be removed, however to ensure backward compatibility you can create something like this:

var chrome = chrome||browser;

Or isolate the scope with IIFE

(function (chrome) {
    //seu codigo vai aqui
})(chrome||browser);
Another specifies situation for Desktop notifications that switches between browsers is requireInteraction , which is not supported by Firefox and Opera, only by Chrome, the next example below has a way around the exception caused in Firefox, but unfortunately it is not possible to force the user to interact, since it is still a deficiency of other browsers.

How to create notifications?

Notifications have the following basic properties:

  • type : notification type, most browsers only support basic
  • title notification title
  • message : notification message
  • requireInteraction : if set to true the notification will not close by itself, it will be necessary to use chrome.notifications.clear(<id>);

To use it, you must add manifest.json to your notifications :

"permissions": [
    "notifications"
]

A simple example would be something like:

function notificar(id, titulo, texto, imagem)
{
    var props = {
        "type": "basic",
        "title": titulo,
        "message": texto,
        "requireInteraction": true //Só fecha a notificação quando a pessoa clicar
    };

    if (imagem) {
        //Pega a imagem dentro do add-in com getURL
        props.iconUrl = browser.extension.getURL(imagem);
    }

    try {
        chrome.notifications.create(id, props, function() {});
    } catch (ee) {
        //Firefox não suporta requireInteraction e causa uma exception então o código abaixo é para tentar novamente

        //Deleta o requireInteraction se não suportado
        delete props.requireInteraction;

        //Gera a notificação sem requireInteraction
        chrome.notifications.create(id, props, function() {});
    }
}

And to detect the click on the generated popup-notification use:

//Quando clicar em qualquer notificação vai disparar este evento e pelo parametro "id" poderá detectar qual notificação você fechou
chrome.notifications.onClicked.addListener(function(id, byUser) {
    //Fecha/remove a notificação após o clique
    chrome.notifications.clear(id);
});

The usage will look like this:

notificar(1, "foo bar", "Olá mundo");
notificar(2, "foo bar", "Olá mundo");
notificar(3, "foo bar", "Olá mundo", "icones/image.png");

Test example

The code could be applied to tests like this in background.js :

(function (chrome) {

    function notificar(id, titulo, texto, imagem)
    {
        var props = {
            "type": "basic",
            "title": titulo,
            "message": texto,
            "requireInteraction": true
        };

        if (imagem) {
            props.iconUrl = browser.extension.getURL(imagem);
        }

        try {
            chrome.notifications.create(id, props, function() {});
        } catch (ee) {
            //Firefox não suporta requireInteraction e causa uma exception então o código abaixo é para tentar novamente

            delete props.requireInteraction;

            chrome.notifications.create(id, props, function() {});
        }
    }


    chrome.notifications.onClicked.addListener(function(id, byUser) {
        chrome.notifications.clear(id); //Fecha/remove
    });

    //Gerar uma notificação aleatória a cada 5 segundos
    setTimeout(function () {
         notificar(
             Date.now(), //Gera uma ID por tempo, a ID pode ser qualquer coisa, só não pode ser repetida
             'Titulo',   // Titulo da notificação
             'Foo Bar',  // Texto na notificação
             'icones/icone1.png' //Ícone opcional
         );
    }, 5000);

})(chrome||browser); //Talvez no futuro o Firefox só suporte pelo "browser." isso fará ser retrocompativel

It's important to note that notifications do not hold if you close and reopen the browser, so you can restore them by using something like localStorage to save the data and every time you reopen the browser it generates from a localStorage and when firing the chrome.notifications.onClicked.addListener event you should remove the notification data from localStorage as well.

    
03.01.2018 / 21:26