how to communicate between a options page and background page of chrome extension

前端 未结 1 1810
忘了有多久
忘了有多久 2021-02-09 18:14

I face a problem. Through message passing I transferred DOM data from content script to background page. What i would like to know is how you can establish a communication chann

1条回答
  •  逝去的感伤
    2021-02-09 18:51

    It makes sense for the second approach not work. Options.html is not "alive" all of the time, only when the options page is up. Hence, it cannot listen to requests from the content script. That's exactly what "background" is for.

    As for the first approach (using getBackgroundPage()), I never used this method myself, but it seems to bring back only the DOM of the background page, and therefore you cannot access the variables in the background js.

    Your best shot should be to send a request from the options page to the background page, asking for this value, e.g.:

    Content script:

    chrome.extension.sendRequest({greeting: "retrieveAddr"}, function(response) {
      // do something with response.addr...
    });
    

    Background page:

    chrome.extension.onRequest.addListener(
      function(request, sender, sendResponse) {
        switch (request.greeting) {
        case "maprender"):
          alert("reached here sendin resp"+request.name);
          Addr_details.place = request.name;
          sendResponse({farewell: "goodbye"});
          break;
        case "retrieveAddr":
          sendResponse({addr: Addr_details});   
    
        default:
          sendResponse({}); // snub them.
      });
    });
    

    Another, easier but hackier solution is to use localStorage to pass info between the options and background pages, as they both share the same one.

    0 讨论(0)
提交回复
热议问题