简体   繁体   中英

How to communicate to a long-running React Chrome Extension via the default_popup modal?

I am making a Chrome Extension that overlays a choice div over the current web page.

I have spent considerable time studying how to develop a Chrome Extension with React and with regular ways to inject HTML and JS. More React-specific information is needed to put this together.

My goal is to achieve this:

  1. Click default_popup which reveals some extension settings

  2. Toggle overlay ON

  3. A full-screen overlay covers the current webpage

  4. Dismiss the default_popup modal

  5. The overlay is still there because the React-based extension is still running

  6. Click default_popup which reveals the extension settings again

  7. Toggle overlay OFF

I have followed every tutorial I can find on Google and dissected every React Chrome Extension I can find in GitHub, and this my question that arises after that.

Can anyone provide an example or describe exactly what needs to be done to achieve the above steps?

The most important thing I can't find from any tutorials or code spelunking is how do I inject a React App as a Chrome Extension and have it talk to the default_popup modal?

To communicate between the popup ( i assume you mean browserAction here) and any open tab the easiest way would be through background script. So in manifest.json you add

"background": {
   "scripts": ["background.js"]
}

and then in background.js file you can listen to events emitted from contentScript or browserAction scripts with onMessage

//background.js
chrome.runtime.onMessage.addListener( function(message){
    // do some actions depending on message object
    // e.g. add or remove overlay with tabs api 
} 

and send message from your popup with sendMessage like this

chrome.runtime.sendMessage({ action: "TOGGLE_OVERLAY", toVisible: true}) 

please note: if you want to send messages to content scripts you should use tabs API sendMessage instead

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