【问题标题】:Communicate between popup and content script in chrome在 chrome 中的弹出窗口和内容脚本之间进行通信
【发布时间】:2016-12-21 20:22:08
【问题描述】:

我正在尝试构建一个 chrome 扩展,但我无法将消息从弹出窗口发送到内容脚本。请告诉我问题出在哪里。

弹窗脚本代码:

         $(document).ready(function(){ 
            $('#button').click(function(){
              chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
                     chrome.tabs.sendMessage(tabs[0].id, {message: "hello"});
        });
    });
});

内容脚本代码:

chrome.extension.onMessage.addListener(
 function(request, sender) {
  alert("Contentscript has received a message from from background script: '" + request.message + "'");
  });

这是 manifest.json :

{
  "manifest_version" : 2,
  "name" : "First My Chrome Extension",
  "version" : "0.0.1",
  "description" : "The first web-app using chrome extension technology",
  "icons" : {
    "16" : "images/icon16px.png",
    "48" : "images/icon48px.png",
    "128" : "images/icon128px.png"
  },


 "background": {
    "scripts": ["scripts/background.js"]

  },



  "browser_action" :{
    "default_icon":{
      "48" : "images/icon48px.png"
    },
    "default_title" : "Nghoangvutn",
    "default_popup" : "popup.html"
  },
  "content_scripts":[
  {
    "matches":[
      "<all_urls>"
      ],
    "js" : [
      "scripts/jquery.js",
      "scripts/content.js"
      ]

  }
    ],

  "permissions" : [
    "tabs",
    "storage"
    ]

}

【问题讨论】:

  • 弹出窗口和网页控制台中是否有任何错误信息?
  • 没有错误信息。它只是行不通。也许消息传递失败。不知道哪里出了问题
  • 如果您通过设置断点调试弹出窗口和内容脚本,则此类问题在几秒钟或几分钟内即可解决。
  • 是的,谢谢 woxxom,它工作了。

标签: javascript google-chrome-extension


【解决方案1】:

内容脚本代码应更新为使用以下方法chrome.runtime.onMessage.addListener。注意从chrome.extensionchrome.runtime 的变化。

chrome.runtime.onMessage.addListener(
 function(request, sender) {
   alert("Contentscript has received a message from from background script: '" + request.message + "'");
});

【讨论】:

  • 我听从了你的帮助,但没有任何改变,内容脚本不起作用。
  • 它应该使用清单文件动态或静态添加到页面中。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多