简体   繁体   English

获取网页字段的内容到Javascript变量[Firefox Addon-SDK]

[英]Get content of web page field to Javascript variable [Firefox Addon-SDK]

I am using Firefox Addon SDK to develop Firefox Mozilla add-on/extension. 我正在使用Firefox Addon SDK开发Firefox Mozilla附加/扩展。 Now I would like to get field value "user" from displayed web site, when the user clicks on my Add-on button.Web page's form looks like this: 现在,当用户点击我的附加按钮时,我想从显示的网站获得字段值“user”。网页的表单如下所示:

<form name="input" action="html_form_action.asp" method="get">
   Username: <input type="text" name="user" id="user" value="name of the user">
<input type="submit" value="Submit">

So I need to display the value "name of the user" in my Add-on textbox, which I had created inside of the Add-on. 所以我需要在我的附加组件文本框中显示值“用户名”,这是我在附加组件中创建的。

But I can't figured out how to pass data FROM THE WEBSITE to the ADDON VARIABLE/SITE. 但我无法弄清楚如何将数据从网站传递到ADDON VARIABLE / SITE。

You need to do this using a content script. 您需要使用内容脚本执行此操作。 Assuming you have html like this: 假设你有像这样的HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form><input type="text" id="txt-field" value="this is the value"/></form>
</body>
</html> 

...what you need to do is use the page-mod module to attach a content script to the page that can then fetch the value and send it back. ...您需要做的是使用page-mod模块将内容脚本附加到页面,然后可以获取值并将其发回。

main.js: main.js:

const data = require('self').data;

var currentVal = false;

require('page-mod').PageMod({
  include: 'https://some.url/index.html',
  contentScriptFile: data.url('script.js'),
  onAttach: function(worker) {
    worker.port.on('val', function(data) {
      currentVal = data;
      console.log(data);
    });
  }
});

script.js: 的script.js:

self.port.on('fetch-value', function() {
  self.port.emit('val', document.querySelector('#txt-field').value);
});

This is a very simple example just to show you how communication from main.js and a content script can work. 这是一个非常简单的示例,只是为了向您展示main.js和内容脚本之间的通信是如何工作的。 For more, I highly recommend you read the documentation on content scripts: 有关更多信息,我强烈建议您阅读有关内容脚本的文档:

https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM