如何将消息从弹出脚本传递到后台脚本到内容脚本

时间:2016-06-17 22:41:43

标签: javascript jquery dom google-chrome-extension message-passing

编辑 - 添加后台脚本

我需要从我的chrome扩展程序中的弹出脚本中获取一条消息到内容脚本。它应该在单击弹出窗口内的按钮时发送消息。

阅读更多内容后,您似乎无法直接在弹出脚本和内容脚本之间进行通信。

我想我需要去: popup.js> background.js>的script.js

我已经尝试过这样做,但我似乎无法让它发挥作用。有几种不同的方法可以实现消息传递,但是没有太多关于此用例的文档。

这里是代码(它现在似乎没有传递消息):

popup.js

/* when something is saved in local storage... */
        chrome.storage.sync.set({'myFilter': filter}, function(){

            /* send message to background script */
            chrome.runtime.sendMessage({greeting: "hello from popup"}, function(response) {
                console.log(response.farewell);
            });
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              chrome.tabs.sendMessage(tabs[0].id, {greeting: "new filter saved"}, function(response) {
                console.log(response.farewell);

              });
            });
        });

background.js

 /*listen for message from popup, send message to content script */
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a background script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello from popup") {
        alert("message passed to background script");
        console.log("message passed to background script");

         /* send message to content script */
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                  chrome.tabs.sendMessage(tabs[0].id, {greeting: "popup sent message"}, function(response) {
                    console.log(response.farewell);

                  });
                });
         return true;
       sendResponse({farewell: "goodbye"});
    }
    return false;
  });

的script.js

    /* get notice from background script*/
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 == "popup sent message") {
        alert("message passed to content script");
        console.log("message passed to content script");
        location.reload();
        walkWithFilter();
         return true;
       sendResponse({farewell: "goodbye"});
    }
    return false;
  });

的manifest.json

{
  "manifest_version": 2,
  "name": "filter",
  "description": "This extension allows twitter users to filter content in their feed",
  "version": "1.0",
  "content_scripts": 
  [
    {
      "matches": ["*://*/*"],
      "js": ["bower_components/jquery/dist/jquery.min.js", "script.js"],
      "run_at": "document_end"
    }
  ],

  "permissions": [
    "tabs",
    "storage",
    "contextMenus",
    "background",
    "https://twitter.com/",
    "http://twitter.com/"  
  ],

  "icons": {
    "16": "fa-moon.png"
  },

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

  "browser_action": {       
   "default_title": "filter",
    "default_icon": "fa-moon.png",
    "default_popup": "popup.html"
  }
}

现在这样做什么都没有 - 当我按下点击事件按钮时,没有弹出警告信息,也没有任何内容打印到控制台。

应该如何运行:

1)用户在弹出窗口中输入输入'保存按钮'并点击保存

2)点击保存按钮,输入保存在localstorage中(此部分有效)

3)点击保存按钮,消息从popup.js发送到script.js告诉 它已将新输入保存到localstorage

4)Script.js接收消息并打印到常规控制台"传递消息"

我这样做的原因是我需要让内容脚本在收到新输入已保存在本地存储中的通知时做一些逻辑。这看起来合情合理吗?

2 个答案:

答案 0 :(得分:2)

你实际上可以直接去 popup.js> script.js ,因为弹出窗口也可以访问后台页面的消息api。

<强>的manifest.json

{
  "manifest_version": 2,
  "name": "filter",
  "description": "This extension allows twitter users to filter content in their feed",
  "version": "1.0",
  "content_scripts": 
  [
    {
      "matches": ["<all_urls>"],
      "js": ["script.js"],
      "run_at": "document_end"
    }
  ],

  "permissions": [
    "tabs",
    "storage",
    "contextMenus",
    "background",
    "https://twitter.com/",
    "http://twitter.com/"  
  ],

  "icons": {
  },

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

  "browser_action": {       
    "default_title": "filter",
    "default_popup": "popup.html"
  }
}

<强> popup.html

<button id="save-button">save-button</button>
<script src="/popup.js" type='text/javascript'></script>

<强> popup.js

document.getElementById("save-button").onclick = function(){
    console.log("clicked button");

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if(tabs.length == 0){ 
            console.log("could not send mesage to current tab");
        }else{
            chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello, how are you content script?"}, function(response) {
                console.log("received message from content script: "+response.farewell);
            });
        }
    });
}

<强>的script.js

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


    console.log("received message from popup: "+request.greeting);

    sendResponse({farewell: "I'm good, thank you popup!"});
});

答案 1 :(得分:0)

您的权限列表中缺少一条非常重要的邮件传递权限,即用于与浏览器的标签系统进行交互的tabs

使用

替换manifest.json中的权限数组
   provided "org.springframework.boot:spring-boot-starter-tomcat"