Chrome扩展程序:点击通知后创建新标签 [英] Chrome extension: Creating a new tab after clicking on the notification

查看:681
本文介绍了Chrome扩展程序:点击通知后创建新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数notify(notifyMessage){
var options = {
type:basic,
title:My Extension,
消息:notifyMessage,
iconUrl:hello.png
};
chrome.notifications.create(,options,function(notificationId){
setTimeout(function(){
chrome.notifications.clear(notificationId,function(){});
},2000);
});
chrome.notifications.onClicked.addListener(function(notificationId,byUser){
chrome.tabs.create({url:http://www.google.com});
});

$ / code>

使用这个函数,当我触发 notify 首次点击通知,它会创建一个选项卡。当我第二次触发它并单击时,它会创建两个选项卡等。我应该如何重新组织我的代码,以便每次只创建一个选项卡? 解决方案 chrome.notifications.onClicked.addListener 方法会为您打开的通知中的每个添加一个onclick监听器延期。每次调用此方法时,都会向其中的所有添加另一个onclick监听器:如果您调用该方法3次,则每个通知都会有3个点击监听器,并且每个监听器都会打开一个选项卡。



要修复代码,只需在notify函数外部添加点击处理程序,即可添加一个onclick监听器。



<注意:在点击侦听器中指定的回调将被传递给实际点击的通知的通知ID,这样,如果您同时打开几个通知,就可以区分通知。



通知ID是 chrome.notifications.create 的第一个参数。在这里,您总是通过,所以您最多只能打开一个通知。


function notify(notifyMessage) {
    var options = {
        type: "basic",
        title: "My Extension",
        message: notifyMessage,
        iconUrl: "hello.png"
      };
    chrome.notifications.create("", options, function(notificationId) {
      setTimeout(function(){
        chrome.notifications.clear(notificationId, function(){});
      }, 2000);
    });
    chrome.notifications.onClicked.addListener(function(notificationId, byUser) {
        chrome.tabs.create({url: "http://www.google.com"});
    });
}

With this function, when I trigger notify for the first time and click on the notification, it creates one tab. When I trigger it for the second time and click, it creates two tab, etc. How should I reorganize my code to make it create only one tab each time?

解决方案

The chrome.notifications.onClicked.addListener method adds an onclick listener to each of the notifications opened by your extension. Each call to this method adds another onclick listener to all of them: if you call that method 3 times, your notifications will each have 3 click listeners, and each one will open a tab.

To fix your code, you simply have to add the click handler outside of the notify function, to add only one onclick listener.

Note: the callback specified in the click listener will be passed the notification id of the notification that was actually clicked on, so that you can differentiate notifications if you open several at the same time.

The notification id is the first parameter of chrome.notifications.create. Here, you always pass "", so you'll always have at most one notification opened.

这篇关于Chrome扩展程序:点击通知后创建新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆