Search code examples
javascriptpluginsnpapi

NPAPI - use javascript objects/functions from within plugin


I've read about how to obtain a handle on DOM elements. This was a very helpful link: http://forums.mozillazine.org/viewtopic.php?f=27&t=1521545

My question now is, can I get a handle on a Javascript var/object I've created, or arbitrary functions?

On page load, i have a script executing something like this...

var controller = new Controller()

or

function callme(param1, param2) { ... }

now, from within my plugin, I want to be able to call methods from my controller object. OR, execute that function callme. Is this possible and how would I go about doing this?

Thanks,

Chris


Solution

  • From your link you know how to get the NPObject for the DOM window; from there all you need to know is that all global javascript variables are actually properties of the window.

    var controller = new Controller();
    

    If you've done this in the global scope, then window.controller is your variable, so you just need to do:

    /* Get window object */
    NPObject* window = NULL;
    NPN_GetValue(aInstance, NPNVWindowNPObject, &window);
    
    /* Get document object */
    NPVariant controllerVar;
    NPIdentifier id = NPN_GetStringIdentifier("controller");
    NPN_GetProperty(aInstance, window, id, &controllerVar);
    NPObject* document = NPVARIANT_TO_OBJECT(controllerVar);
    

    You can then access properties on your Controller object or call methods. Note that if controller were a function you could call it with NPN_InvokeDefault.

    BTW, FireBreath automates most of this.