Add-on Builder: multiple workers using a port?

Referring to this question: Add-on Builder: ContentScript and Back to Addon Code?

Here is my addon code:

var widget = widgets.Widget({
  id: "addon",
  contentURL: data.url("icon.png"),
  onClick: function() {
    var workers = [];
    for each (var tab in windows.activeWindow.tabs) {
        var worker = tab.attach({contentScriptFile: [data.url("jquery.js"), data.url("myScript.js")]});
        workers.push(worker);
    }
  }
});

      

And here's myScript.js:

var first = $(".avatar:first");
if (first.length !== 0) {
    var url = first.attr("href");
    self.port.emit('got-url', {url: url});
}

      

Now that I have some workers where I put

worker.port.on('got-url', function(data) {
            worker.tab.url = data.url;
        });

      

Since in another question I only had one worker, but now I have an array of workers.

+2


source to share


1 answer


Code:

// main.js:
var data = require("self").data;
var windows = require("windows").browserWindows;

var widget = require("widget").Widget({
    id: "addon",
    label: "Some label",
    contentURL: data.url("favicon.png"),
    onClick: function() {
        //var workers = [];
        for each (var tab in windows.activeWindow.tabs) {

            var worker = tab.attach({
                contentScriptFile: [data.url("jquery.js"), 
                data.url("inject.js")]
            });

            worker.port.on('got-url', function(data) {
                console.log(data.url);
                // worker.tab.url = data.url;
            });

            worker.port.emit('init', true);
            console.log("got here");
            //workers.push(worker);
        }
    }
});

// inject.js
$(function() {
    self.port.on('init', function() {
        console.log('in init');
        var first = $(".avatar:first");
        if (first.length !== 0) {
            var url = first.attr("href");
            console.log('injected!');
            self.port.emit('got-url', {url: url});
        }    
    });
});

      

Edit: sorry, had to actually run the code, we had a sync issue where the script content was injected before a working listener was set, so the listener was not yet created when the 'got-url' event was emitted. I'll get around this by deferring any action in the content script until the init event is fired into the content script.



Here's an example of working with the builder:

https://builder.addons.mozilla.org/addon/1045470/latest/

The rest of the problem with this example is that it is not possible to determine if the tab was added by our add-in, so we will "leak" or use more memory each time the widget is clicked. A better approach might be to insert the content of the script using the page mod on page load, and only exit the init event in the onclick handler of the widget.

+1


source







All Articles