【问题标题】:Chrome extensions - unload event page immediatelyChrome 扩展 - 立即卸载事件页面
【发布时间】:2012-11-24 10:19:23
【问题描述】:

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

Chrome extension documentation我读到这个:

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

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

这是我的代码:

ma​​nifest.json

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

background.js

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

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

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    代码 a)

    ma​​nifest.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"
      ]
    }
    

    background.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)

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

    ma​​nifest.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"
      ]
    }
    

    background.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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 2021-11-01
      相关资源
      最近更新 更多