Chrome扩展程序 - 在执行任何其他操作之前的runtime.onStartup

时间:2015-10-15 22:26:21

标签: javascript google-chrome-extension

清单的'background'部分中的

persistent = false意味着该背景页面可以从内存中卸载并稍后再次启动。

我有一个变量,我需要在加载和卸载后台页面和浏览器时保存。我很好,我可以使用localStorage或chrome.storage.sync / local。

但是我需要在启动浏览器时更改此变量。我需要在任何其他行动之前做到这一点。

所以,我的代码是:

chrome.runtime.onStartup.addListener(function() {
  localStorage.setItem("variable", 0);
});
//main actions:
var my_var = localStorage.getItem("variable");
my_var += 3;
localStorage.setItem("variable", my_var);

我需要在主要操作之前运行chrome.runtime.onStartup,但我不能,因为chrome.runtime.onStartup事件可以在主要操作之后触发。

每次将后台页面加载到内存时,主要操作都会运行,因为持久性= false。

2 个答案:

答案 0 :(得分:1)

使用chrome.alarms API设置立即执行的警报;它的回调将在onStartup

之后排队
  • event.js:

    chrome.runtime.onStartup.addListener(function() {
        console.log("startup");
        localStorage.variable = 0;
    });
    
    chrome.alarms.create("main", {when: Date.now()});
    chrome.alarms.onAlarm.addListener(function(alarm) {
        console.log("execute");
        if (alarm.name == "main") {
            mainCode();
        }
    });
    
    function mainCode() {
        ...................
        ...................
    }
    
  • 的manifest.json:

    "permissions": ["alarms"],
    

答案 1 :(得分:-1)

我仍然有点困惑,如果我错了,请纠正我:你必须在启动后运行同步功能,然后我认为你需要做出以下改变:

chrome.runtime.onStartup.addListener(function() {

    //chrome.runtime.onStartup finished

    //disable
    //localStorage.setItem("variable", 0);

    //main actions:
    var my_var = localStorage.getItem("variable");
    my_var += 3;
    localStorage.setItem("variable", my_var);
});

在任何其他代码之前启动chrome.runtime.onStartup