nsIPrefBranch observers Topic is solved

Add-ons for Pale Moon and other applications
General discussion, compatibility, contributed extensions, themes, plugins, and more.

Moderators: FranklinDM, Lootyhoof

yami_

nsIPrefBranch observers

Unread post by yami_ » 2018-05-25, 20:50

If I understand documentation correctly, to use nsIPrefBranch observer you need to:
  • Add the observer:

    Code: Select all

    let prefs = Components.classes["@mozilla.org/preferences-service;1"]
    	.getService(Components.interfaces.nsIPrefService)
    	.getBranch("extensions.yami.preftest.");
    prefs.addObserver("", yami.preftest, false);
    
  • Point it to an object with observe method:

    Code: Select all

    yami.preftest = {
    	observe: function observe(sub, topic, data) {
    		if(topic == "nsPref:changed") {
    			/* ... */
    		}
    		return;
    	},
    }
    
For me this works, but is not reliable - it will randomly stop working. I am able to reproduce this on Pale Moon and Basilisk using the attached preftest extension and following steps:
  1. Install preftest
  2. Open add-on manager
  3. Open preftest's options page
  4. Restart the browser (File > Restart...)
  5. After the browser restarts, quickly try to change drop-down menu's selection
  6. "Observer execution counter" should increment
  7. Open a new tab
  8. While on that tab, navigate to any webpage
  9. Switch to the add-on manager's/preftest's options tab
  10. Try to change drop-down menu's selection again
Now the "Observer execution counter" will not increment.
Does anyone have any idea why this is not working correctly?
Attachments
preftest.xpi
the test extension
(2.28 KiB) Downloaded 13 times

JustOff

Re: nsIPrefBranch observers

Unread post by JustOff » 2018-05-26, 07:36

This is because you declared prefs as a local variable, so js garbage collector kills it. You need something like this:

Code: Select all

	init: function init(e /* object */) /* void */ {
		yami.prefs = Components.classes["@mozilla.org/preferences-service;1"]
			.getService(Components.interfaces.nsIPrefService)
			.getBranch("extensions.yami.preftest.");
		yami.prefs.addObserver("", yami.preftest, false);
	},

yami_

Re: nsIPrefBranch observers

Unread post by yami_ » 2018-05-26, 09:11

JustOff wrote:This is because you declared prefs as a local variable, so js garbage collector kills it.
Thanks JustOff, now it works correctly.

Locked