Chrome extension: when new window is opened background script is moved to the new one

Viewed 24

I have faced the strange behavior of background script in Chromium. Here is the script:

let windowId;

chrome.windows.onCreated.addListener((window) => alert(`${windowId}: onCreated ${window.id}`));
chrome.windows.onBoundsChanged.addListener((window) => alert(`${windowId}: onBoundsChanged: ${window.id}`));
chrome.windows.onRemoved.addListener((window) => alert(`${windowId}: onRemoved: ${JSON.stringify(window)}`));

chrome.windows.getCurrent({}, window => {
    alert(`getCurrent: ${window.id}`);
    windowId = window.id;
});

setInterval(() => alert(`setInterval: ${windowId}`), 3000);

When first window is opened, it outputs current windowId (in my case always 1). With some interval (3 seconds) it outputs window number: setInterval: 1.

When second window is opened by clicking Ctrl-N in Windows, I expect that onCreated event will show information.

But actually I see getCurrent: 29 (where 29 is the new window ID) and I do not see 1: onCreated 29 event.

And each 3 seconds I see only setInterval: 29. At the same time I do not see setInterval: 1.

When I move first window, I see 29: onBoundsChanged: 1. The second window now works and it reacts to the movement of the first one. And first window does not alert on any changes. It looks like the background script in the frist window does not work.

So, it means that background script in the window 1 does not work, it started on the window 29. If all environment like all variables etc. moved to the new background script?

The initial task was to communicate between first and any new windows opened during extension work. I assumed to react on onCreated event and make data exchange. Also I expected to inject some script to the newly created window and make interraction.

How can I do this?

Now I see that only last window works, and all precedent windows don't process messages, events etc.

Thanks in advance!

P. S. Environment: Windows, customized Chromium (based on 93.0.4544.0 Chromium version), Manifest V2.

manifest.json file:

{
  "manifest_version": 2,
  "background": {
    "scripts": [...],
    "persistent": true
  },
  "permissions": [
    "activeTab",
    "alarms",
    "cookies",
    "downloads",
    "history",
    "proxy",
    "storage",
    "tabs",
    "webNavigation",
    "webRequest",
    "webRequestBlocking",
    "<all_urls>"
  ]
}
0 Answers
Related