无法在Chrome扩展程序

时间:2015-10-29 23:41:42

标签: google-chrome-extension message content-script

我在我的背景页面上有这个:

function go(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

}

go();

这是我的内容脚本:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      alert(request.greeting);
  });

我预计在启用应用程序时启动警报,但没有任何事情发生。我错过了什么吗?

编辑:manifest.json:

{
  "manifest_version": 2,

  "name": "Naming",
  "description": "any",
  "version": "1.0",

  "permissions": [
    "tabs",
    "activeTab",
    "https://google.com.br/"
  ],

 "background": {"scripts":["background.js"]},

  "content_scripts": [
    {
      "js": ["CLAWS_Content_Script.js", "jquery.js"],
      "css": ["CLAWS_Content_Script_CSS.css"],
      "matches": ["<all_urls>"]

    }
  ],

  "web_accessible_resources": [
        "CLAWS_Sem_Imagens.html",
        "icone_XVermelho.png"
  ]


}

内容脚本被加载,因为它提供的其他功能完美无缺。控制台没有错误。

1 个答案:

答案 0 :(得分:0)

在浏览器启动或启用扩展程序时发送消息,但此时没有活动内容脚本来接收消息。同样,当您重新加载网页时,您的背景页面不会重新加载,因此不会发送任何消息,因此不会收到任何消息。

如果您真的想要the alert to launch as I enable the extension,请通过chrome.tabs.executeScript手动注入内容脚本,在这种情况下,您不需要manifest.json中的"content_scripts"部分。

相关问题