Can't save Variable from Port.on when writing a Firefox Addo

Talk about add-ons and extension development.
Post Reply
kim366
Posts: 3
Joined: March 21st, 2016, 11:03 am

Can't save Variable from Port.on when writing a Firefox Addo

Post by kim366 »

I am very new to writing FF addons, but I am trying my best. So I have this code, which I got from MDN:

Code: Select all

var tabs = require("sdk/tabs");

tabs.on('activate', function(tab) {
  var worker = tab.attach({
    contentScript: 'self.port.emit("html", document.body.innerHTML);'
  });
  worker.port.on("html", function(message) {
   console.log(message)
  })
});
When I change it to:

Code: Select all

var contentHtml = '';

var tabs = require("sdk/tabs");

tabs.on('activate', function(tab) {
  var worker = tab.attach({
    contentScript: 'self.port.emit("html", document.body.innerHTML);'
  });
  worker.port.on("html", function(message) {
    contentHtml = message
  })
});

console.log(contentHtml);
it logs an empty string. Why is that?

What is the proper way of putting this into the variable contentHtml?

Thank you, Kim
lithopsian
Posts: 3664
Joined: September 15th, 2010, 9:03 am

Re: Can't save Variable from Port.on when writing a Firefox

Post by lithopsian »

Timing. In the second example, you initialise a variable called contentHtml, declare an anonymous function to be called when a tab is attached, which then declares another anonymous function to be called when a port message is received. Then, before any callbacks can possibly be made, you immediately log the value of contentHtml, still a blank string. Then later, you maybe get a message, assign it to contentHtml, and ... and nothing :)
kim366
Posts: 3
Joined: March 21st, 2016, 11:03 am

Re: Can't save Variable from Port.on when writing a Firefox

Post by kim366 »

Huh, interesting. So how do I do it? I know that it has something to do with asynchronous functions, so I|ll look into those. Thanks for hyour help!
kim366
Posts: 3
Joined: March 21st, 2016, 11:03 am

Re: Can't save Variable from Port.on when writing a Firefox

Post by kim366 »

Actually I only copied that code, because I wanted the page HTML in a string. When I did

Code: Select all

document.body.innerHTML
, it said document was undefined, so I had to do something with tabs, and this was the only thing that worked. Is there a better way of doing it?
Post Reply