1

I'm at the moment looking for a class or something that would make it possible to synchronously communicate with the Javascript of a tab.

It's a pain to dynamically manipulate a website with the default API. It would be so great if we could do something like this:

var tabs = require('sdk/tabs');
var exampleElement = tabs.activeTab.document.getElementById('exampleId');
console.log(exampleElement.innerHTML);
exampleElement.style.width = '200px';

So is there a class/lib that allows me to do this or can you tell me how I could make something like that possible? I'm really new to this...

Forivin
  • 14,780
  • 27
  • 106
  • 199

2 Answers2

2

As mentioned here, it's not possible with the addons SDK. You can use non-SDK code for synchronous communication, but if Firefox switches to a multi-process architecture, it will stop working. It's generally recommended to stick with the asynchronous APIs for new code.

Community
  • 1
  • 1
jb_314
  • 1,373
  • 2
  • 17
  • 28
  • But shouldn't it be possible to wrap the asynchronous API into a synchronous one? Somehow like this maybe: http://pastebin.com/D5X0iLvs Probably not with a while loop, but maybe there is something else that you could use? – Forivin Dec 08 '13 at 07:39
  • See http://stackoverflow.com/questions/9121902/call-an-asynchronous-javascript-function-synchronously – jb_314 Dec 08 '13 at 07:56
2

One option would be to wrap async calls using the built-in promise library:

https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/core/promise.html

This style of development is a little more obtuse than synchronous calls but it does avoid 'callback hell' when using multiple / nested callbacks.

therealjeffg
  • 5,790
  • 1
  • 23
  • 24
  • Okay that is good news. So it is actually possible. But has anyone written a nice class that would allow me to "directly" call a tabs javascript (like in my example from the question) so far? – Forivin Dec 09 '13 at 04:53
  • I don't really understand the promises-API. :( How could I make this piece of code synchronous: http://pastebin.com/KnSuPxGc Could you give me an example please? I'd really appreciate it. – Forivin Dec 09 '13 at 06:58
  • You can't make it synchronous - the SDK intentionally avoids synchronous apis. Either you suck it up and use callbacks or you learn promises. It's just JS... – therealjeffg Dec 09 '13 at 18:40