Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Communication from chrome extension to web page


I know it's possible to postMessage from a web page to a chrome extension and get an ok response back to the web page, but is it possible the other way around ?

My question "I need to be able to sent a request into a webpage and wait for a response that I can use in the extension. Maybe not with postMessage ?"

I know the docs says "Only the web page can initiate a connection." (https://developer.chrome.com/extensions/messaging#external-webpage)

This is what I have tried so far.

background.js

chrome.extension.sendMessage("Hello from extension to webpage");
window.postMessage("Hello from extension to webpage");
chrome.tabs.sendMessage(TAB_ID, "Hello from extension to webpage");

webpage.js (not part of the extension)

window.onmessage = (event) => {
  // Waiting for that message.
  console.info("Event received ", event);
}
window.chrome.runtime.connect(CHROME_EXTENSION_APP_ID).onMessage.addListener(function (){
  function(request, sender, sendResponse) {
     console.info("Event received from the extension", event);
  }
})  

Any idea will be appreciated :)


Solution

  • You can use chrome.tabs.executeScript API to do this.

    var dataToWebPage = {
      text: 'test',
      foo: 1,
      bar: false
    };
    
    chrome.tabs.executeScript({
      code: '(' + function(params) {
        //This function will  work in webpage
        console.log(params); //logs in webpage console 
        return {
          success: true,
          response: "This is from webpage."
        };
      } + ')(' + JSON.stringify(dataToWebPage) + ');'
    }, function(results) {
      //This is the callback response from webpage
      console.log(results[0]); //logs in extension console 
    });
    

    Please note that it needs tabs permission.