Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

Firefox addon sdk: retrieving value from a different site based on clipboard content


I just got started with firefox addons to help my team fasten up our work, what i am trying to create: When being on a specific site (let's call it mysite.com/input) i want to fill out automatically an input with an id: "textinput" from the value that is stored on the clipboard. Yeah it is simple yet it would be simply enough to paste it, wouldn't it?... now here is the twist:

I need an other form of the value: on the clipboard it is x/y/z. There is a database site (let's call it database.com) on which searching like database.com?s=x/y/z would directly give the page from where it is possible to gain the correct value as it has an id: #result

I got lost how to properly communicate between page and content scripts, i'm not even sure in what order should i use the pagemod and the page-worker

Please help me out! Thank you!


Solution

  • The basic flow is this:

    • In your content script, you get the value form the form, somehow. I'll leave that up to you.

    • Still in the content script, you send the data to main.js using self.port.emit:

    Code:

    self.port.emit('got-my-value', myValue);
    
    • In main.js, you would then receive the 'got-my-value' event and make a cross-domain request using the request module.

    Code:

    require('page-mod').PageMod({
        include: 'somesite.com',
        contentScriptFile: data.url('somescript.js'),
        onAttach: function(worker) {
            worker.port.on('got-my-value', function(value) {
                require('request').Request({
                    url: 'http://someurl.com',
                    onComplete: function(response) {
                        console.log(response);
                        // maybe send data back to worker?
                        worker.port.emit('got-other-data', response.json);
                    }
                }).post();
            });
        }
    });
    
    • If you need to receive the data back in the original worker, you would another listener for the event coming back.

    Code:

    self.port.on('got-other-data', function(value) {
        // do something
    })