0

我是 Chrome 扩展程序开发的新手。我编写了一个扩展程序,每次创建新选项卡时都会显示通知。它可以工作,但是如果我打开一个选项卡并立即打开另一个选项卡,则通知将仅显示第一个选项卡。

Chrome 扩展文档中,我读到了这个:

一旦事件页面空闲了一小段时间(几秒钟),就会调度 chrome.runtime.onSuspend 事件。

显然它解释了为什么第二个标签没有通知。是否可以立即卸载事件页面(即一旦显示通知),而无需等待几秒钟?

这是我的代码:

清单.json

{
    "name": "test",
    "version": "1.0",
    "description": "notification test",
    "manifest_version": 2,
    "permissions": [ "tabs", "notifications" ],
    "background": { "scripts": ["background.js"], "persistent": false }
}

背景.js

var notification = webkitNotifications.createNotification(
    '48.png',
    'hello',
    'this is a test'
);

chrome.tabs.onCreated.addListener(function(tab) {
    notification.show();
});
4

1 回答 1

0

代码 a)

清单.json

{
    "name": "test",
    "version": "1.0",
    "description": "notification test",
    "manifest_version": 2,
    "permissions": [ "tabs", "notifications" ],
    "background": { "scripts": ["background.js"], "persistent": false },
    "web_accessible_resources": [
    "48.png"
  ]
}

背景.js

function notify(tab){
    console.log(tab);
    var notification = webkitNotifications.createNotification(
        '48.png',
        'hello',
        'this is a test'
    );
    notification.show();
}

chrome.tabs.onCreated.addListener(notify);

在此解决方案中,如果由于https://code.google.com/p/chromium/issues/detail?id=162543而第一次/在另一个选项卡之后创建新选项卡,您将看到两个通知。但是在这里,您会被事件页面而不是背景页面所吸引。

代码 b)

通过将事件页面制作为背景页面,您可以获得所需的功能运行;但是,如果您特别关注它,请不要使用事件页面。

清单.json

{
    "name": "test",
    "version": "1.0",
    "description": "notification test",
    "manifest_version": 2,
    "permissions": [ "tabs", "notifications" ],
    "background": { "scripts": ["background.js"], "persistent": true },
    "web_accessible_resources": [
    "48.png"
  ]
}

背景.js

function notify(tab){
    console.log(tab);
    var notification = webkitNotifications.createNotification(
        '48.png',
        'hello',
        'this is a test'
    );
    notification.show();
}

chrome.tabs.onCreated.addListener(notify);
于 2012-11-25T10:19:58.433 回答