最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React.js Chrome Extension - How to store data from Background.js in a variable inside React? - Stack Overflow

programmeradmin4浏览0评论

Hello what I am trying to do is send a string that I derived from my background.js file and send it to my react app (specifically a ponent used by App.js). I have /* global chrome */ at the top of the ponent.js file and am able to store data on the chrome local storage however my question is how do I make sure that I can store this data in a variable before the React app is processed? For example, even though I am able to assign a variable inside the ponent the data from chrome storage, it is only stored after my React app is created. What I'm trying now is to send a chrome message in background.js and try to listen for this message in the ponent to store the variable however the listener does not seem to be working. Any help would be appreciated! (p.s. this is using functional ponents but help in class ponents would also be appreciated)

ponent.js:

chrome.runtime.onMessage.addListener(function(msg) { 
   if(msg.type == "USER_STORED") {
      chrome.storage.local.get(['name'], function(result) { 
         console.log("User is " + result.name); 
         username = result.name; 
      }); 
   }
});

background.js:

chrome.storage.local.set({name: username}, function() { 
      console.log("User is set to " + username);
      chrome.runtime.sendMessage({type: "USER_STORED" });
      console.log("message sent"); 
    }); 

    // Open extension window
    console.log("WINDOW_OPENED"); 
    var win = window.open("index.html", "extension_popup"); 

Console: Extension console image

Hello what I am trying to do is send a string that I derived from my background.js file and send it to my react app (specifically a ponent used by App.js). I have /* global chrome */ at the top of the ponent.js file and am able to store data on the chrome local storage however my question is how do I make sure that I can store this data in a variable before the React app is processed? For example, even though I am able to assign a variable inside the ponent the data from chrome storage, it is only stored after my React app is created. What I'm trying now is to send a chrome message in background.js and try to listen for this message in the ponent to store the variable however the listener does not seem to be working. Any help would be appreciated! (p.s. this is using functional ponents but help in class ponents would also be appreciated)

ponent.js:

chrome.runtime.onMessage.addListener(function(msg) { 
   if(msg.type == "USER_STORED") {
      chrome.storage.local.get(['name'], function(result) { 
         console.log("User is " + result.name); 
         username = result.name; 
      }); 
   }
});

background.js:

chrome.storage.local.set({name: username}, function() { 
      console.log("User is set to " + username);
      chrome.runtime.sendMessage({type: "USER_STORED" });
      console.log("message sent"); 
    }); 

    // Open extension window
    console.log("WINDOW_OPENED"); 
    var win = window.open("index.html", "extension_popup"); 

Console: Extension console image

Share Improve this question edited Jul 28, 2020 at 7:42 struggleatreact asked Jul 28, 2020 at 5:48 struggleatreactstruggleatreact 331 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You use wrong approach. You don't need to send such messages from background at all, nor need to listen for them in your popup window. Just add chrome.storage.local.get call into your popup entry point (likely index.js) and wrap ReactDOM.render with its callback. Something like this:

chrome.storage.local.get(null, function (data) {
  ReactDOM.render(
    <App {...data} />,
    document.getElementById('root')
  )
});

Then, the data from chrome.storage will be available in all sub-ponents of the root <App> via props. Something like this:

function YourComponent(props) {
  console.log("User is " + props.name);
  return <h1>Hello, {props.name}</h1>;
}

I think you can directly access the chrome storage API inside the ponentDidMount() method and fetch the variable from the storage.get() and set the value to a state variable.

Try this

manifest.json

{
    "name": "test2",
    "version": "0.0.1",
    "manifest_version": 2,
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
    "background": {
        "scripts": [
            "./background/background.bundle.js"
        ]
    },
    "permissions": [
        "storage",
        "tabs",
        "activeTab"
    ],
    "browser_action": {}
}

background.js

console.log("inside bg script")
let user = "zzzzzzzzz"
chrome.storage.local.set({ name: user }, function () {
    console.log("User is set to" + user);
})
chrome.browserAction.onClicked.addListener((tab) => {
    chrome.tabs.create({
        url: chrome.runtime.getURL("./test.html")
    });
});

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app-root">
    </div>
    <script src="./index.bundle.js"></script>
</body>
</html>

index.js (react ponent)

import React from "react";
import ReactDOM from "react-dom";
class MainApp extends React.Component {
    render() {
        return (
            <div>
                <h1>hi</h1>
            </div>
        );
    }
    ponentDidMount() {
        let newThis = this;
        chrome.storage.local.get(['name'], function (result) {
            console.log("User is " + result.name);
// you can use the variable or set to any state variable from here
        });
    }
}
ReactDOM.render(<MainApp />, document.getElementById("app-root"))

the required value will be available in the ponentDidMount() functions storage.get() methods callback. You can set to the ponent state variable or use it as your wish.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论