chrome.extension.getBackgroundPage() doesn't work with manifest_version: 3

Viewed 1104

When I invoke a function of backgroud.js in popup.js, if manifest_version is 2, it works; if manifest_version is 3, it doesn't work. Why? How can I do with manifest_version: 3


manifest.json

//version 2
{
  "manifest_version": 2,
  ......
  "background": {
    "scripts": ["background.js"]
  },
}

//version 3
{
  "manifest_version": 3,
  ......
  "background": {
    "service_worker": "background.js"
  },
}

popup.js

var bg = chrome.extension.getBackgroundPage();
var userName = bg.getUserName();
console.log(bg);

background.js

var userName = "John";
console.log("background");

function getUserName() {
  return userName;
};

snapshot in manifest_version 2 enter image description here

snapshot in manifest_version 3 enter image description here

1 Answers

I search a article mentioned "Things to note about a service worker", the following is the third note:

"It's terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's onfetch and onmessage handlers. If there is information that you need to persist and reuse across restarts, service workers do have access to the IndexedDB API."

Above the question case, I guess that background.js(as Service Worker) has terminated when popup.js invoke the function of background.js in Manifest-V3 , so popup.js can't invoke function of background.js(as Service Worker) in Manifest-V3

https://developers.google.com/web/fundamentals/primers/service-workers

Related