javascript - 有没有办法在谷歌浏览器的通知中插入操作按钮

标签 javascript google-chrome google-chrome-extension notifications

我需要在 chrome 中添加一个带有“允许”和“拒绝”按钮的通知。当用户点击“允许”按钮时,它必须导航到一个网站,当用户点击“拒绝”按钮时通知框不应该再出现了。那是它必须关闭。我该怎么做?请帮帮我 这是我的 background.js

        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 updateIcon(){

      var req = new XMLHttpRequest();
      req.addEventListener("readystatechange", function() {
       if (req.readyState == 4) {
       if (req.status == 200) {
        localStorage.item=req.responseText;
        //alert(localStorage.item);
        if(localStorage.item==1){
          chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
          chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
          chrome.browserAction.setBadgeText({text:""});   
        }
        else{
        chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
        chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
        chrome.browserAction.setBadgeText({text:""}); 
        }

      } else {
        // Handle the error
        alert("ERROR: status code " + req.status);
      }
    }
    });
       req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
   req.send(null);
       }

       var myNotificationID = null;

           /* For demonstration purposes, the notification creation 
      * is attached to the browser-action's `onClicked` event.
      * Change according to your needs. */
          chrome.browserAction.onClicked.addListener(function() {
             chrome.notifications.create("", {
    type:    "basic",
    iconUrl: "http://calpinemate.com/icon_128.png",
    title:   "REMINDER",
    message: "It's time to go to this super-cool site !\nProceed ?",
    contextMessage: "It's about time...",
    buttons: [{
        title: "Yes, get me there",

    }, {
        title: "Get out of my way",

    }]
      }, function(id) {
    myNotificationID = id;
    });
    });

  /* Respond to the user's clicking one of the buttons */
    chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
      if (notifId === myNotificationID) {
      if (btnIdx === 0) {
        window.open("...");
    } else if (btnIdx === 1) {
        saySorry();
    }
    }
 });

    /* Add this to also handle the user's clicking 
      * the small 'x' on the top right corner */
     chrome.notifications.onClosed.addListener(function() {
     saySorry();
       });

        /* Handle the user's rejection 
    * (simple ignore if you just want to hide the notification) */
         function saySorry() {
      alert("Sorry to bother you !");
      }

编辑 background.js

  var myNotificationID = null;
  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.addEventListener("readystatechange", function() {
     if (req.readyState == 4) {
    if (req.status == 200) {

        var item=req.responseText;

        if(item==1){
          chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
          chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
          chrome.browserAction.setBadgeText({text:""});   
        }
        else{
        chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
        chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
        chrome.browserAction.setBadgeText({text:""}); 
        }

    } else {

        alert("ERROR: status code " + req.status);
    }
    }
  }); 
    req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
     req.send(null);
       }
    var notification=chrome.notifications.create("", {
    type:    "basic",
    iconUrl: "/path/to/notification/icon.png",
    title:   "REMINDER",
    message: "It's time to go to this super-cool site !\nProceed ?",
    contextMessage: "It's about time...",
    buttons: [{
        title: "Yes, get me there",
        iconUrl: "/path/to/yesIcon.png"
    }, {
        title: "Get out of my way",
        iconUrl: "/path/to/noIcon.png"
    }]
   }, function(id) {
    myNotificationID = id;
});
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (notifId === myNotificationID) {
    if (btnIdx === 0) {
        window.open("http://www.calpinemate.com/");
    } else if (btnIdx === 1) {
        saySorry();
    }
     }
   });

   chrome.notifications.onClosed.addListener(function() {
saySorry();
 });

    function saySorry() {
    alert("Sorry to bother you !");
     }
   notification.show();

最佳答案

您需要的一切都由 chrome.notifications API 提供。例如:

list .json:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": [
            "./bg/background.js"
        ]
    },

    "browser_action": {
        "default_title": "Test Extension"
    },

    "permissions": ["notifications"]
}

background.js:

var myNotificationID = null;

/* For demonstration purposes, the notification creation 
 * is attached to the browser-action's `onClicked` event.
 * Change according to your needs. */
chrome.browserAction.onClicked.addListener(function() {
    chrome.notifications.create("", {
        type:    "basic",
        iconUrl: "/path/to/notification/icon.png",
        title:   "REMINDER",
        message: "It's time to go to this super-cool site !\nProceed ?",
        contextMessage: "It's about time...",
        buttons: [{
            title: "Yes, get me there",
            iconUrl: "/path/to/yesIcon.png"
        }, {
            title: "Get out of my way",
            iconUrl: "/path/to/noIcon.png"
        }]
    }, function(id) {
        myNotificationID = id;
    });
});

/* Respond to the user's clicking one of the buttons */
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
    if (notifId === myNotificationID) {
        if (btnIdx === 0) {
            window.open("...");
        } else if (btnIdx === 1) {
            saySorry();
        }
    }
});

/* Add this to also handle the user's clicking 
 * the small 'x' on the top right corner */
chrome.notifications.onClosed.addListener(function() {
    saySorry();
});

/* Handle the user's rejection 
 * (simple ignore if you just want to hide the notification) */
function saySorry() {
    alert("Sorry to bother you !");
}

关于javascript - 有没有办法在谷歌浏览器的通知中插入操作按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20188792/

相关文章:

javascript - 有没有办法在谷歌服务器上存储谷歌浏览器扩展的信息?

javascript - 为什么加载新页面时 Chrome.storage.sync 存储会重置?

javascript - 如何将数据动态添加到 jquery DataTable 中?

javascript - 如何开始收集 ICE 候选人以进行对等连接

javascript - Django - 使用 JavaScript 进行实时更新

jquery - jScrollPane:Webkit中拖动jspDrag位时水平滚动条向左移动

javascript - 来自 chrome 扩展的套接字连接被代理/防火墙阻止

google-chrome-extension - 将文件类型与 Chrome Packaged App 关联

javascript - 如何在呈现页面之前在用户脚本中切换 CSS 文件?

javascript - 在新窗口中打印带有标签的html文本