javascript - Chrome 扩展程序 : Clicking notification opens multiple tabs

标签 javascript jquery google-chrome-extension notifications

chrome.runtime.onMessage.addListener(function(msg, sender) {

    var options = {
        type: "basic",
        title: msg.title,
        message: "Price: " + msg.price + "\nFinished ",
        iconUrl: "icon.png"
    };

    chrome.notifications.create(options);

    chrome.notifications.onClicked.addListener(function() {
        chrome.tabs.create({url: "https://example.com/" + msg.link + "/a"});
    });

});

当我第一次单击通知时,它会打开一个新选项卡。当我第二次单击通知时,它会打开两个新选项卡,依此类推。如何让通知只打开一个选项卡?

我看过Chrome extension: Creating a new tab after clicking on the notification并尝试执行建议的操作(如下所示),但这会导致单击通知时什么也不会发生。

chrome.runtime.onMessage.addListener(function(msg, sender) {

    var options = {
        type: "basic",
        title: msg.title,
        message: "Price: " + msg.price + "\nFinished ",
        iconUrl: "icon.png"
    };

    chrome.notifications.create(options);

});

chrome.notifications.onClicked.addListener(function() {
    chrome.tabs.create({url: "https://example.com/" + msg.link + "/a"});
});

最佳答案

您需要跟踪 notificationId 及其应指向哪个链接。例如:

var linkMap = {};  //outside the listener function

chrome.runtime.onMessage.addListener(function(msg, sender) {

    var options = {
        type: "basic",
        title: msg.title,
        message: "Price: " + msg.price + "\nFinished ",
        iconUrl: "icon.png"
    };

    chrome.notifications.create(options, function (notifId){
        linkMap[notifId] = msg.link;
    });

});

chrome.notifications.onClicked.addListener(function(notifId) {
    chrome.tabs.create({url: "https://example.com/" + linkMap[notifId] + "/a"});  //use it here.
});

关于javascript - Chrome 扩展程序 : Clicking notification opens multiple tabs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47517835/

相关文章:

javascript - 为什么总是返回 "undefined"

google-chrome-extension - Chrome 扩展存储 onChanged() 未检测到更改(未触发)

javascript - JS - 当新文本元素添加到页面时如何再次运行脚本

javascript - 具有部分的 Ractive 递归 - 导致超出最大调用堆栈大小

javascript - jQuery 验证验证禁用的输入字段

jquery - jquery 获取复选框的当前状态

javascript - Ajax 完成回调不等待不是函数

javascript - 操作 jquery 对话框的 div 内容

javascript - Vue.js 如何上传图像并在之后运行自定义方法

javascript - 我可以使用 setTimeout 而不是点击处理程序吗?