Search code examples
javascriptjqueryfirefox-addonmozillafirefox-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. 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:

<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.


Solution

  • You need to do this using a content script. Assuming you have html like this:

    <!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.

    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:

    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. For more, I highly recommend you read the documentation on content scripts:

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