Search code examples
javascriptnpapi

How do I use NPAPI to receive calls from javascript on the page?


I am working on a plugin that needs to receive calls from javascript. Specifically, it needs to be able to give a callback function to javascript, and the javascript needs to be able to call that function later with at least a string argument. The javascript looks something like this (ideally):

var callback = null;
var setCallback = function(cb) {
  var callback = cb;
};
var input = document.getElementById('my_text_input_field');
input.onkeypress = function(ev) {
  // Did the user press enter?
  if (ev && ev.which == 13) {
    callback(input.value);
    return false;
  }
};

I'm imagining my C code looks something like this, so far:

void SetCallback(void (*callback)(const char*)) {
  NPVariant npCallback;
  OBJECT_TO_NPVARIANT(callback, npCallback);
  NPVariant args[] = { npCallback };
  size_t nargs = 1;
  NPVariant result;
  // gFuncs is an NPNetscapeFuncs pointer
  NPIdentifier method = gFuncs->getstringidentifier("setCallback");
  // gJavaScriptAPI is an NPObject pointer
  gFuncs->invoke(gInstance, gJavaScriptAPI, method, args, nargs, &result);
}

Is this a reasonable start? If so, what do I need to do in the callback function to handle calls to it? If not, what is the correct way to do something like this, or is it not possible in NPAPI?

Thank you in advance.


Solution

  • Basically what you need to do is provide a NPObject that implements InvokeDefault; you pass that back to the page in response to some Invoke or GetProperty call, and then javascript can call it as a function any time with whatever arguments you wish.

    For more information about NPObjects in general, see http://npapi.com/tutorial3

    FireBreath abstracts all of this so that 90% of the heavy lifting is done for you; if you haven't looked at it I highly recommend it.