基本的谷歌chrome扩展消息传递不起作用

Basic google chrome extension message passing not working

本文关键字:扩展 消息传递 不起作用 chrome 谷歌      更新时间:2024-04-01

我一直试图让chrome扩展的消息传递正常工作,但console.log(response)给了我未定义的消息。我已经查看了文档中的消息传递和stackoverflow,但在我的情况下,它不起作用。我不知道为什么。

myscript.js:

chrome.extension.sendRequest({greeting: "hello"}, function(response) {
    console.log(response);
    return true;
});

background.js:

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
      sendResponse({farewell: "goodbye"});
      return true;
 });

manifest.json

{
  "manifest_version": 2,
  "name": "nameasf",
  "description": "asfasaf",
  "version": "1.0",
  "permissions": [
    "tabs",
    "http://somedomain.com/"
  ],
    "content_scripts": [
    {
      "matches": ["http://somedomain.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"],
      "all_frames": true
    }
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

您正在使用过时的chrome.extension.sendRequest
请改用chrome.runtime.sendMessage

(注意:您已经在使用新的chrome.runtime.onMessage,因此您不必更改侦听器端的任何内容。)


几个旁注:

  • 对于这里提供的代码,您不需要任何权限(尤其是不需要强大的tabs权限)
  • 只要可能,最好使用非持久性后台页面(也称为事件页面),因为它们对资源更友好