Question

I have an addon that every 5 minuets or so checks an rss feed for a new post, and if there is one, it displays an alert(). Problem is, I'm afraid that if the user opens multiple windows, that when there's a new post a millions of alerts will popup saying the same thing. Is there anyway to have just one "brain" running at a time?

Thanks in advance!

Was it helpful?

Solution

Look up something called "Javascript shared code modules" or JSMs.

Primary docs are here:

https://developer.mozilla.org/En/Using_JavaScript_code_modules

Each .js file in your addon that needs shared memory will open with the following line:

Components.utils.import("resource://xxxxxxxx/modules/[yourFilenameHere].jsm", com.myFirefoxAddon.shared);

The above line opens [yourFilenameHere].jsm and loads its exported (see below) functions and variables into the com.myFirefoxAddon.shared object. Each instance of that object loaded will point to the same instance in memory.

Note that if you want to have any hope of you addon making it past moderation, you will need to write all your code in a com.myFirefoxAddon.* type object as the goons at AMO are preventing approval of addons that do not Respect the Global Namespace

The biggest caveat for JSM is that you need to manually export each function that you want to be available to the rest of your code... since JS doesn't support public/private type stuff this strikes me as a sort of poor-man's "public" support... in any case, you will need to create an EXPORTED_SYMBOLS array somewhere in your JSM file and name out each function or object that you want to export, like this:

var EXPORTED_SYMBOLS = [
    /* CONSTANTS */
    "SERVER_DEBUG",
    "SERVER_RELEASE",

    "LIST_COUNTRIES",
    "LIST_TERRITORIES_NOEX",

    /* GLOBAL VARIABLES */
    /* note: primitive type variables need to be stored in the globals object */
    "urlTable",
    "globals",

    /* INTERFACES */
    "iStrSet",

    /* FUNCTIONS */
    "globalStartup",

    /* OBJECTS */
    "thinger",
    "myObject"

]

OTHER TIPS

[edited] Modules are not the right solution to this problem, since the code will still be imported into every window and the whatever listeners/timers you set up will run in every window. You should be careful with using modules for this -- all the timers/callbacks must be set up in the module code (not just using the observer object defined in the module) and you shouldn't use any references to the window in the module.

The right way to do this is I would prefer to write an XPCOM component (in JS). It's somewhat complicated, yes and I don't have a handy link explaining how to do it. One thing: implementing it using XPCOMUtils is easier, older documentation will throw lots of boilerplate code on you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top