简体   繁体   中英

How to implement push notification in Chrome

I am writing a chrome extension that will receive at some points messages. I would like to have that little red circle on the bottom-right side of my ico extension with 1,2,3... depending on the number of messages received by the user. More, if the user pushes on the extension and reads that/those message(s), that little circle will disappear

I've read some nice articles about how will I be able to implement such a thing but for now, all that I've come with is a basic notification which disappear after ten seconds.

manifest.json

{
    "name": "Notification with Audio",
    "description": "notification",
    "manifest_version": 2,
    "version": "1",
    "permissions": [
        "notifications"
    ],
    "background": {
        "scripts": [
            "background.js"
        ]
    }
}

background.js

createNotification(); audioNotification();

function audioNotification(){
    var yourSound = new Audio('yourSound.mp3');
    yourSound.play();
}

function createNotification(){
    var opt = {type: "basic",title: "Your Title",message: "Your message",iconUrl: "your_icon.png"}
    chrome.notifications.create("notificationName",opt,function(){});

    //include this line if you want to clear the notification after 5 seconds
    setTimeout(function(){chrome.notifications.clear("notificationName",function(){});},5000);
}

Could somebody describe the process of achieving what I want ? It's a must to use the GCM service ?

If you want to present an icon that displays the number of unread messages and does something on click, then you want a Browser Action .

A browser action can either open a small page on click called a popup (useful if you want to display something) or trigger an onClicked event in the background page (useful if you want to do something else, like open a web page).

As for the counter, the standard way is to use the badge , which can be set with setBadgeText and setBadgeBackgroundColor . Alternatively, you can draw some sort of custom badge over your icon using a <canvas> and update the icon dynamically with setIcon - but that would go against UI traditions of Chrome.

徽章样本


As for push messages - GCM API is a ready solution, but you can implement your own; WebSockets would be a suitable technology to do it.

If you have a more concrete question about that, ask it separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM