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

I am working on a plugin that should receive calls from javascript. In particular, it should be able to give a javascript callback function, and javascript should be able to call this function later, at least with a string argument. 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 imagine my C code looks something like this:

 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 that a reasonable start? If so, what do I need to do in the callback function to handle calls? If not, what is the correct way to do something like this, or is this not possible in NPAPI?

Thanks in advance.

+4
source share
2 answers

Basically, you need to provide an NPObject that implements InvokeDefault; you pass this back to the page in response to an Invoke or GetProperty call, and then javascript can call it as a function at any time with any arguments you want.

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

FireBreath abstracts all this so that 90% of the hard work is done for you; if you have not looked, I highly recommend it.

+4
source

Maybe I'm wrong about that, but in Internet Explorer you use window.external . But, of course, MSIE is a different architecture from NPAPI based on Netscape, so I cannot be sure. Anyway, you may find this tip useful if you need to do this in MSIE.

+1
source

Source: https://habr.com/ru/post/1346862/


All Articles