0

我正在嘗試構建推送通知。
我試圖實現一個從web引用的隨機代碼。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"} 
} 

的問題是擴展在鉻越來越加載,但它並沒有對代碼作出迴應。沒有顯示通知。 :(請幫助。

回答

1

我沒有用過webkitNotifications但是我使用chrome.notifications API的實現鉻通知。 這是我如何做的。

在你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被調用,並創建一個監聽調用 updateValues爲每10秒。
  2. 一旦updateValues被調用,它 使用 sendMessage API向runtime.onMessage偵聽器發送消息。
  3. 在onMessage監聽器中,我們使用chrome.notifications.create創建了 通知。

就是這樣。

編輯: 我的代碼更大,我複製粘貼它的部分。

+0

面臨同樣的問題。發生了什麼是我沒有得到任何形式的錯誤,但我沒有任何通知。我嘗試編輯和實施你的代碼.. –

+0

@ChiragKamat 保存我建議作爲background.js的腳本並編輯你的manifest.json到 「background」:{ \t「scripts」:[「background。js「] } 這會在啓動插件時加載腳本 –

+1

@ChiragKamat這是否解決了您的通知問題? –