如何将用户输入从HTML面板传递到firefox Addon SDK中的Addon脚本

时间:2017-05-07 12:10:07

标签: firefox firefox-addon firefox-addon-sdk

我正在使用Addon SDK。我对如何将用户输入传递给我的插件index.js感到困惑。我查看了内容脚本,但这并不是我想要的。当用户点击Addon按钮时,我会弹出一个HTML页面。这是HTML代码:

<html>
<head>
<style type="text/css" media="all">
textarea {
margin: 10px;
}
body {

        background-color:white;
      }
    </style>
  </head>

  <body>

  <form> 
      Enter name: <br>
      <input type="text" id="txt-field">
      <input type="submit" value="Add">
  </form>
  </body>
</html>

一旦用户点击HTML中的add按钮,我需要将用户输入的文本传递给我的main.js文件,然后我想永久存储它,除非用户手动删除它。这是index.js:

var { ToggleButton } = require('sdk/ui/button/toggle');
var sdkPanels = require("sdk/panel");
var self = require("sdk/self");
var storage = require("sdk/simple-storage"); 

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

var myPanel = sdkPanels.Panel({
  contentURL: "./text-entry.html",
  onHide: handleHide
});

function handleChange(state) {
  if (state.checked) {
    myPanel.show({
      position: button
    });
  }
}

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

你能指点我怎样才能实现这样的目标?

1 个答案:

答案 0 :(得分:0)

要将值从HTML面板页面传递到Addon脚本,您需要添加内容脚本。由于我的面板是可信的(在插件内部而不是外部网页),因此您可以通过将脚本附加到面板来实现在HTML面板中输入的传递值。面板代码如下所示(代码来自:this link

const vector<double>& getDataSet() const {return dataSet;}
string getTimeStamp() const {return time_stamp;}

然后,使用面板输入文本的脚本代码(在此示例中,文本以enter结尾)并将值发送到Addon,如下所示:

<html>
<head>
    <style type="text/css" media="all">
      textarea {
        margin: 10px;
      }
      body {
        background-color: gray;
      }
    </style>
  </head>
  <body>
    <textarea rows="13" cols="33" id="edit-box"></textarea>
    <script src="get-text.js"></script>
  </body>
</html>

接收该值并将其发布在// When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); addon.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user can // just start typing. addon.port.on("show", function onShow() { textArea.focus(); }); 中的插件代码为:

console.log