如何在某些网站扩展页面操作上显示通知

时间:2015-03-23 16:29:21

标签: google-chrome google-chrome-extension

我正在开发适用于某些网站的扩展程序页面操作我希望每当用户访问网站时添加通知我都不满意地址栏中的图标,当通知显示时,通知如何显示用户访问特定网站?

我有这些代码

后台,显示地址栏中特定网站的图标

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {

if (~tab.url.indexOf('specificsite.com.br')) {
chrome.pageAction.show(tabId);
}

});

通知代码

createNotification();
audioNotification();

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

  function createNotification(){
  var opt = {type: "basic",title: "Your Title",message: "Your      message",iconUrl: "128.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(){});},10000);

}

1 个答案:

答案 0 :(得分:2)

您可以使用message passing通过内容脚本完成检测某些网站上的切换,然后通知后台页面以显示该页面的通知。您的内容脚本应使用chrome.runtime.sendMessage发送消息,后台页面应使用chrome.runtime.onMessage.addListener收听:

我创建了示例代码并测试了它与我合作:

内容脚本(myscript.js):

if(onCertainWebsitesNeedNotificationAppearTrue) {
    // send message to background script
    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {

});
}

背景页面:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        //alert("good");
        if (request.greeting == "hello")
        createNotification();
    });
function createNotification(){
     var opt = {type: "basic",title: "Your Title",message: "Your  message",iconUrl: "128.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(){});},10000);
}

另请注意在清单中注册内容脚本的代码和权限,如:

    "permissions": ["notifications"],
    "content_scripts": [
    {
      "matches": ["http://www.certainwebsiteone.com/*", "http://certainwebsitetwo.com/*"],
      "js": ["myscript.js"]
    }
  ]