Funkafied
Funkafied

Reputation: 53

Add-on Builder: Multiple Workers Using 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 is 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 multiple workers where do I put

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

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

Upvotes: 2

Views: 526

Answers (1)

therealjeffg
therealjeffg

Reputation: 5830

The code would be:

// 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, should have actually run the code, we had a timing issue there where the content script was injected before the worker listener was set up, so the listener was not yet created when the 'got-url' event was emitted. I work around this by deferring any action in the content script until the 'init' event is emitted into the content script.

Here's a working example on builder:

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

The remaining issue with this example is that there is no way to tell if a tab has been injected by our add-on, so we will 'leak' or use more memory every time the widget is clicked. A better approach might be to inject the content script using a page-mod when it is loaded, and only emit the 'init' event in the widget's onclick handler.

Upvotes: 1

Related Questions