如何使用 port.emit 传达包含带有附加脚本的按钮的简单 html 页面

How to communicate a simple html page containing a button with an add-on script using port.emit

我正在尝试实现我的第一个 Firefox 附加组件,所以我完全是个初学者。

我一直在阅读 Firefox 网页上的 [page-mod][1] 文档。我还是不明白该怎么做。

基本上在一个基本的 html 页面中我有一个按钮,我想要的是以下内容:

如果我点击按钮,按钮会调用 Javascript 函数 runBash()(在 html 页面内声明)并且此函数可以与 index.js 通信(添加- 在脚本上)。看似简单,却让我抓狂

[更新代码]

index.js / main.js 附加代码:

var { ToggleButton } = require('sdk/ui/button/toggle');
  var panels = require("sdk/panel");
  var self = require("sdk/self");
  var data = require("sdk/self").data;
  var pageMod = require("sdk/page-mod");

  pageMod.PageMod({
    include: data.url("./bash.html"),
    contentScriptFile: data.url("./content-script.js"),
    contentScriptWhen: "ready", // script will fire when the event DOMContentLoaded is fired, so you don't have to listen for this
    attachTo: ["existing", "top"],
    onAttach: function(worker) {
      worker.port.on("bash", function() {
        //var bash = child_process.spawn('/bin/sh', ['/root/tfg/data/test.sh']);
        alert("IT WORKS!");
      });
    }
  });


  var button = ToggleButton({
    id: "my-button",
    label: "UPF",
    icon: {
      "16": "./favicon-16.ico",
      "32": "./favicon-32.ico",
      "64": "./favicon-64.ico"
    },
    onChange: handleChange
  });

  var panel = panels.Panel({
    contentURL: self.data.url("./panel.html"),
    onHide: handleHide
  });

  var lynisAlreadyExecuted = false;
  function handleChange(state) {

      if (lynisAlreadyExecuted == false) {
        var child_process = require("sdk/system/child_process");

        var ls = child_process.spawn('/usr/sbin/lynis', ['-c', '-q']);

        ls.stdout.on('data', function (data) {
          console.log('stdout: ' + data);
        });

        ls.stderr.on('data', function (data) {
          console.log('stderr: ' + data);
        });

        ls.on('close', function (code) {
          console.log('child process exited with code ' + code);
        });
        lynisAlreadyExecuted = true;
      }

    if (state.checked) {
      panel.show({
        position: button
      });
    }
  }

  function handleHide() {
    button.state('window', {checked: false});
  }

  function enableButton2() {
    var information = String(navigator.userAgent);
    var checkOS = information.includes("Linux",0);
    var checkBrowser = information.includes("Firefox",0);
    if(checkOS && checkBrowser){
      alert("Your system meets the minimum requirements! :)");
      document.getElementById("button2").disabled = false;
    }
    else{
      alert("Your System is not compatible");
    }         
  }

内容-script.js:

function runBash() {
    // rest of your code
    self.port.emit("bash");
}

bash.html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../css/layout.css" type="text/css" media="screen">
<link rel="stylesheet" href="../css/menu.css" type="text/css" media="screen">

</head>
<body>
    <script src="content-script.js"></script>

    <input type="button" value="CallBash" onclick="runBash();">

</body>
</html>

所以你混淆了你的主要 JS 文件,它基本上是你的扩展的背景页面,以及内容脚本,它将是注入的 JS。在您的 package.json 文件中,您指定 main:

{
  "name": "my-addon",
  "title": "My Addon",
  "id": "12345678",
  "description": "Does cool things.",
  "author": "me",
  "version": "1.0",
  "main": "main.js", <--- this is your main
  "permissions": {"private-browsing": true}
}

main.js中,您可以使用require和其他SDK功能。对于您的 pageMod,您需要指定一个单独的 JS 文件(内容脚本),该文件将被注入 pageMod 目标的 HTML:

编辑:不要在 HTML 中包含带有 <script> 标签的内容脚本,它由 pageMod:

插入
<body>
    <!-- <script src="content-script.js"></script> don't put this here --> 

    <input type="button" value="CallBash" onclick="runBash();">

</body>

此外,作为替代方案,我使用 worker.on (main.js) 和 self.postMessage (content-script.js)。示例:

pageMod.PageMod({
    include: data.url('bash.html'),
    contentScriptFile: data.url("content-script.js"), //<-- this is the content script
    contentScriptWhen: "ready",
    attachTo: ["existing", "top"],
    onAttach: function (worker) {
        worker.on("message", function(data) {
            if (data['action'] == 'bash') {
                worker.postMessage({'action':'did_bash'});
            }
        }
    }
});

然后在content-script.js:

function runBash() {
    self.postMessage({'action':'bash'});
}

self.on('message', function (reply) {
    if (reply['action'] == 'did_bash') {
        console.log('It works!');
    }
}