Google Chrome Extension- Messages + call to function between popup page and content script

前端 未结 1 848
时光说笑
时光说笑 2021-02-10 11:08

In a Google Chrome extension I want to pass messages between a content script and a popup page. I also want a function in the content script to be fired when a signal to do this

相关标签:
1条回答
  • 2021-02-10 11:54

    Content scripts can only send a message to the background page. If you want to send a message from a content script to a popup, you have to:

    1. Send the message from the Content script to the background page.

      chrome.runtime.sendMessage( ...message... , function() { /*response*/ });
      
    2. Receive the message at the background.

      chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { ... });
      
    3. Pass the message to the popup. To get a reference to the global window object of the popup, use chrome.extension.getViews. Note: Unlike most of the other chrome APIs, this method is synchronous:

      var popupWindows = chrome.extension.getViews({type:'popup'});
      if (popupWindows.length) { // A popup has been found
          // details is the object from the onMessage event (see 2)
          popupWindows[0].whatever(message, sendResponse);
      }
      
    4. In the popup, define the whatever method.

      function whatever(message, sendResponse) {
          // Do something, for example, sending the message back
          sendResponse(message);
      }
      
    5. When sendResponse (4) is called, details.sendResponse (see 3) is called. This, in turn, calls function() { /*response*/ } from 1.

    Note: chrome.runtime.sendMessage/onMessage is only supported in Chrome 26+. Use chrome.extension.sendMessage if you want to support older browsers as well.

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