簡體   English   中英

Chrome推送通知

[英]Chrome push Notification

我正在嘗試建立Chrome推送通知。
我試圖實現從網絡引用的隨機代碼。

代碼如下:

notification.html

<script>
    function shows(){

    var notify= webkitNotifications.createNotification('icon48.png','My notification',
    'hi buddy');    
    notify.show();
    }
    if(webkitNotifications){
        setInterval(function()
        {
            shows();
            }, 1000);
    }else{
    chrome.tabs.create({url : "error.html"})
    }

</script>

並且在error.htm中

您的擴展名中有錯誤

manifest.JSON中

{
    "manifest_version": 2,
    "name": "My Extension",
    "version": "1",
    "description" : "Display every 5 sec",
    "icons" : {"48" :"icon48.png"},
    "permissions" : ["tabs","notifications"],
    "background": {"page": "notifications.html"}
}

問題是擴展程序正在chrome中加載,但是它不響應代碼。 沒有顯示通知。 :( 請幫忙。

我沒有使用webkitNotifications,但是我使用chrome.notifications API實現了chrome通知。 這就是我做的。

在您的background.js中

編寫一個發送消息的代碼。

function updateValues(){
           var messageString = 'updated';
           chrome.runtime.sendMessage({
                            body : messageString
                        });
}

updateValues();
setInterval(updateValues, 10000);

立即添加一個偵聽器。 在經常更新值的函數之外。

chrome.runtime.onMessage.addListener(function(msg, sender) {
    var message = msg.body;

    chrome.notifications.onClicked.removeListener(openTab);

    chrome.notifications.create(getNotificationId(), {
        title : 'Test Update Notification',
        iconUrl : 'notification.png',
        type : 'basic',
        message : message
    }, function(id) {
    });

    chrome.notifications.onClicked.addListener(openTab);
});

function openTab(notificationId) {
   var onClickLink = "http://www.mywebsitenotificationstest.com/";
        chrome.tabs.create({
            url : onClickLink
        });
    }

function getNotificationId() {
    var id = Math.floor(Math.random() * 9007199254740992) + 1;
    return id.toString();
}

而已。

基本上,當js被加載時

  1. 將調用updateValues()API,並創建一個偵聽器,以每10秒調用一次updateValues。
  2. 調用updateValues后,它將使用sendMessage API將消息發送到runtime.onMessage偵聽器。
  3. 在onMessage偵聽器內部,我們已編寫了使用chrome.notifications.create創建通知的代碼。

而已。

編輯:我的代碼更大,我復制了其中的粘貼部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM