Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google chrome extension - How to interact with background.js from the popup?

Is there any way to pass information between the popup.html (or popup.js) and a background script?

I'd like the popup to display information from a user's account or allow them to log in, but have the background.js handle the authentication and other logic. I have background.js declared in the manifest, but there seems to be no indication that it's being used at all.

Edit: If I'm going about this all wrong and there's a better way to do this, that would be great too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note that the background page and the popup live in the same process (the extension process), so one page can get the DOM window of the other and then call functions or set variables directly. For example, the popup can call chrome.extension.getBackgroundPage to modify the background:

chrome.extension.getBackgroundPage().variable = 42;

and the background page can call chrome.extension.getViews to get the popup:

var popups = chrome.extension.getViews({type: "popup"});
if (0 < popups.length)
  popups[0].variable = 42;

Another way to set shared variables is by using traditional DOM APIs, since each extension gets a fake origin (such as "eakjnniffhfegdpfehmnpcmjiameincp"). So when you modify localStorage, document.cookie, or IndexedDB on the background, it can be read back in the popup.

That said, you may still want to use the message passing APIs even within pages in the extension process, since it may make your code more uniform. Message passing is the only way to communcate with content scripts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...