如何使用port.emit与包含带有附加脚本的按钮的简单html页面进行通信

Ger*_*era 8 html javascript firefox firefox-addon firefox-addon-sdk

我正在尝试实现我的第一个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");
    }         
  }
Run Code Online (Sandbox Code Playgroud)

内容的script.js:

function runBash() {
    // rest of your code
    self.port.emit("bash");
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

小智 4

因此,您正在混合主 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}
}
Run Code Online (Sandbox Code Playgroud)

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

<script>编辑:不要在 HTML 中包含带有标签的内容脚本,它是通过以下方式插入的pageMod

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

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

</body>
Run Code Online (Sandbox Code Playgroud)

另外,作为替代方案,我使用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'});
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

然后在content-script.js

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

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