about sending messages among bg.html, popup.html and contentscript.js

后端 未结 1 987
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 04:16

In my extension, when a button named mybuttonl in popup.html is clicked, it sends a message \"getvar\" to contentscript.js

1条回答
  •  伪装坚强ぢ
    2021-01-01 04:53

    onRequest.addListener and sendRequest is part of Chrome's extension Messaging. Which is located here http://developer.chrome.com/extensions/messaging.html

    Basically, you listen for a request using "onRequest.addListener" that someone sent from triggering a "sendRequest".

    In your case, you put a "onRequest.addListener" in your content script to listen for requests coming from the Popup (using sendRequest). And from your content script, you can return a response back to your popup to handle what is happening. In your popup, you have direct access to the background page using chrome.extension.getBackgroundPage().

    If you want your content script to communicate to your background page as well (which is not needed since your making stuff more complicated), you can add a "onRequest.addListener" to your background page which only listens for requests coming from the content script. To do that, Message Passing explains it perfectly. "sender.tab" if true, is a content script.

    The example below (untested) shows what I mean about message passing. Remember, try to keep stuff simple, not complex.

    Example

    Popup.html

    chrome.tabs.getSelected(null, function(tab) {
      chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) {
        console.log(response.data);
      });
    });
    

    ContentScript.js

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
      if (request.method == "fromPopup") {
        // Send JSON data back to Popup.
        sendResponse({data: "from Content Script to Popup"});
    
        // Send JSON data to background page.
        chrome.extension.sendRequest({method: "fromContentScript"}, function(response) {
          console.log(response.data);
        });
      } else {
        sendResponse({}); // snub them.
      }
    });
    

    BackgroundPage.html

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
      // From content script.
      if (sender.tab) {
        if (request.method == "fromContentScript")
          sendResponse({data: "Response from Background Page"});
        else
          sendResponse({}); // snub them.
      }
    });
    

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