开发者

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 use开发者_JS百科r 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.


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.


I may be completely wrong about this, but in Internet Explorer, you use window.external. But of course MSIE is a different architecture from Netscape-based NPAPI, so I can't be sure. Anyway, you might find this tip useful if you had to do this in MSIE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜