如何在chrome扩展中插入通知操作按钮

How to insert notification action buttons in chrome extension?

本文关键字:插入 通知 操作 按钮 扩展 chrome      更新时间:2023-10-06

嗨,我需要开发一个通知,其中有两个按钮执行不同的操作。一个按钮是"标记",另一个是"忽略"。当我点击"标记"按钮时,它必须导航到一个网站。当我点击IGNORE时,通知框应该是不可见的,不应该再显示了。我该怎么做?这是我的背景.js

  var oldChromeVersion = !chrome.runtime;
  function getGmailUrl() {
    return "http://calpinemate.com/";
    }
       function isGmailUrl(url) {
       return url.indexOf(getGmailUrl()) == 0;
      }
    chrome.browserAction.onClicked.addListener(function(tab) {
     chrome.tabs.query({
    url: "http://calpinemate.com/*",
    currentWindow: true
    }, function(tabs) {
    if (tabs.length > 0) {
        var tab = tabs[0];
        console.log("Found (at least one) Gmail tab: " + tab.url);
        console.log("Focusing and refreshing count...");
        chrome.tabs.update(tab.id, { active: true });
         updateIcon();
    } else {
        console.log("Could not find Gmail tab. Creating one...");
        chrome.tabs.create({ url: getGmailUrl() });
         updateIcon();
    }
     });
     });
   function onInit() {
      console.log('onInit');
      updateIcon();
      if (!oldChromeVersion) {
      chrome.alarms.create('watchdog', {periodInMinutes:5});
         }
          }
        function onAlarm(alarm) {
       console.log('Got alarm', alarm);
     if (alarm && alarm.name == 'watchdog') {
    onWatchdog();
   } else {
    updateIcon();
       }
     }
     function onWatchdog() {
      chrome.alarms.get('refresh', function(alarm) {
        if (alarm) {
     console.log('Refresh alarm exists. Yay.');
    } else {
   console.log('Refresh alarm doesn''t exist!? ' +
              'Refreshing now and rescheduling.');
    updateIcon();
   }
  });
 }
    if (oldChromeVersion) {
   updateIcon();
   onInit();
    } else {
        chrome.runtime.onInstalled.addListener(onInit);
        chrome.alarms.onAlarm.addListener(onAlarm);
       }
       function updateIcon(){
    var req = new XMLHttpRequest();
    ...
  }
 });
 req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
 req.send(null);
  }
 var notification = webkitNotifications.createNotification(
 '/icon_128.png',  // icon url - can be relative
'Hello!',  // notification title
'Lorem ipsum...'  // notification body text
 );
 notification.show();

对于任何登录此页面的人,如果他们想在通知中添加按钮,或者想弄清楚为什么没有显示按钮:

此答案详细解释了如何创建通知以及如何添加按钮。


尽管如此,一些Linux发行版上并没有显示这些按钮
这是已知问题(Chrome版本31.0.1650.57仍适用),取决于Linux上的Views版本

编辑:根据,按钮在Linux上也能工作(至少从Chrome 35开始)。

如果您正在构建Chrome扩展,您可以访问一个特殊的通知API,它不需要窃听用户显示桌面通知的权限-Chrome.notifications。

要将按钮添加到通知窗口,您不需要编写任何HTML代码。只需写下:

chrome.notifications.create('yourNotificationName', {
  type: 'basic',
  iconUrl: '...',
  title: 'Calpine something',
  message: 'This is the message displayed by the notification',
  buttons: [
    { title: 'Mark' },
    { title: 'Ignore' }
  ]
}, function callback(notificationId) {
  // nothing necessary here, but required before Chrome 42
});