7

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 :)

robe007
  • 3,523
  • 4
  • 33
  • 59
Nederby
  • 244
  • 3
  • 11
  • 2
    Use a content script and normal DOM messages like CustomEvent. – wOxxOm Apr 21 '17 at 10:35
  • Try checking [Communication with the embedding page](https://developer.chrome.com/extensions/content_scripts#host-page-communication) and in a related SO [post](http://stackoverflow.com/a/19048254/5995040), as stated it is possible if you are using content script. You can also check the [forum](https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/lTUDJYClBF0) that talks about passing message from extension to web page. Hope this helps. – Mr.Rebot Apr 21 '17 at 15:20

1 Answers1

1

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.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Mûhámmàd Yäsår K
  • 1,492
  • 11
  • 24
  • 1
    Does this live in content-script or the webpage? If the former, then is this actually the answer to the original question? content-script ≠ webpage. – Kalnode Jan 02 '23 at 15:34