Chrome extension: store data on background

后端 未结 3 695
情书的邮戳
情书的邮戳 2021-02-04 19:21

I want to be able to store data on background (on my extension) so I can access this data between multiple domains.

Where\'s what I\'m doing:

content-scr

3条回答
  •  孤城傲影
    2021-02-04 20:12

    Content.js

    var someVar = "hey hey!";
    
    chrome.extension.sendRequest({method: "fromContentScript",greeting: someVar}, function(response) {
    
        console.log(response.data); // response back from BG
    
        if(response.who == 'bg'){ // checks if the response is from BG
                //Something happened ...
        }
    
        var responseFromBg = response.data; // the response incase we need to use the message sent back... in this case should be 'hey yourself'
    
    
    });
    

    Background.js

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
      // From content script.
      if (sender.tab) {
        if (request.method == "fromContentScript"){
    
            localStorage.setItem("welcome-message",request.greeting); // in this case there will now be a localStorage variable called 'welcome-message' set with the value of 'hey hey!'. This will be viewable in the chrome:extensions page, click on the 'background.html / generated background.html' then view the 'Development Tools' or in Windows hit 'CTRL + SHIFT + I' and look at the 'LocalStorage' tab...
    
          sendResponse({who: "bg",data: "hey yourself"}); // this is the response sent back, 'who' tells the content page where is responding, so it can do something with the response if needed.
            }else{
          sendResponse({}); // snub them.
            }
      }
    });
    

    Manifest.json // just incase it is a manifest issue you are having... here is most of mine..

    {
      "name": "Name here",
      "version": "1",
      "manifest_version": 2,
      "description": "Enter desc here.",  
        "browser_action": {
        "default_icon": "img/icon16.png",
        "default_popup": "popup.html"
      },    
        "background": {
        "scripts": ["background.js"]
      },
      "permissions": [
        "tabs", "*://*/*"
      ],
        "icons": { "16": "img/icon16.png",
               "48": "img/icon48.png",
              "128": "img/icon128.png" },
      "content_scripts": [
        {
          "matches": ["*://*/*"],
          "js": ["js/jquery-1.7.2.min.js","content_script.js"],
          "run_at": "document_end"
        }
      ]
    }
    

    Would have used your example, but I am in a hurry this morn. I have tried to explain all of the vars as carefully as possible - sorry :(

提交回复
热议问题