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/