从Chrome扩展到网页的通信

nwsw7zdq  于 2023-03-27  发布在  Go
关注(0)|答案(1)|浏览(191)

我知道可以从网页向chrome扩展发布消息,然后在网页上得到一个ok响应,但反过来可能吗?

我的问题“我需要能够将请求发送到网页中并等待可以在扩展中使用的响应。也许不需要postMessage?”

我知道文档说“只有网页可以发起连接。”(https://developer.chrome.com/extensions/messaging#external-webpage)
这是我迄今为止所尝试的。

  • 背景.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(不是扩展的一部分)

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);
  }
})

任何想法将不胜感激:)

ghhkc1vu

ghhkc1vu1#

您可以使用API来完成此操作。

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 
});

请注意,它需要tabpermission

相关问题