简体   繁体   中英

listening only to one event at a time in chrome extension background script

i want the init() function to be called only one time even if the two events were triggered

chrome.tabs.onUpdated.addListener(function callback() {
  init();
});
chrome.tabs.onActivated.addListener(function callback() {
  init();
});

Use a named function for both events and unregister both events inside.

chrome.tabs.onUpdated.addListener(initOnce);
chrome.tabs.onActivated.addListener(initOnce);

function initOnce() {
  chrome.tabs.onUpdated.removeListener(initOnce);
  chrome.tabs.onActivated.removeListener(initOnce);
  init();
}

You can track it with a variable.

let initCalled = false;

Then in your init() function:

function init() {
    if (initCalled) return;
    //rest of init() code here
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM