default_popup中的数据未通过后台脚本传递到content_scripts

时间:2018-07-23 19:30:21

标签: javascript google-chrome firefox google-chrome-extension firefox-webextensions

我正在创建Firefox插件(例如chrome扩展名)。我能够将default_popup中用户选择的值传递给后台脚本,但不能从那里传递给内容脚本。

我的manifest.json

{
  "manifest_version": 2,
  "name": "Beautiful Website",
  "description": "Customize website color based on User selection",
  "version": "1.0",
  "permissions": ["notifications"],
  "background": {
    "scripts": ["background_script.js"]
  },
  "browser_action": {
    "default_icon": "icons/logo_64.png",
    "default_title": "Beautiful Website",
    "default_popup": "index.html"
  },
  "content_scripts":[
    {
        "matches": ["<all_urls>"],
        "js": ["cs.js"]
    }
  ]
}

我的index.html

...
<body>
            <form id="colorForm">
                    <div>
                        <input type="radio" id="red" name="usercolor" value="red" checked />
                        <label for="red">Red</label>
                    </div>
                    <div>
                        <input type="radio" id="green" name="usercolor" value="green" />

                        <label for="green">Green</label>
                    </div>
...
<button type="submit">Submit</button>
 </form>

        </body>
<script src="index_scr.js"></script>

</html>

它给Firefox弹出窗口

enter image description here

然后创建index_scr.js

var form = document.querySelector("form");

form.addEventListener("submit", function(event) {
    var data = new FormData(form);
    var output = "";
    for (const entry of data) {
      output = entry[1];
    };

    browser.runtime.sendMessage({
      userColor: `${output}`
    })

    event.preventDefault();
  }, false);

我的background_script.js。

function handleFormSelection(data){
  browser.notifications.create({
      "type": "basic",
      "title": "Updated Color Page",
      "message": data.userColor.toUpperCase()
  })

}

browser.runtime.onMessage.addListener(handleFormSelection);

browser.browserAction.onClicked.addListener(sendData)

function sendData(tab){
    browser.tabs.sendMessage(tab.id, {data:'dummyData'})
}

内容脚本(cs.js)是

function letsDoThis(data){
    console.log('Inside CS ', data);
}

browser.runtime.onMessage.addListener(letsDoThis)

问题无法获得一种发送/方式将从用户接收的颜色发送到内容脚本的方法。

有人可以帮忙做最后一部分吗?

0 个答案:

没有答案