Rahul Gulati
Rahul Gulati

Reputation: 363

Calling a Javascript API from an NPAPI DLL

I'm writing an extension for Google Chrome that uses an NPAPI DLL. In the invoke method of the NPAPI DLL, I have inserted the following code to print a message to the javascript console:

char* message = "Hello from C++";

// Get window object.
NPObject* window = NULL;
npnfuncs->getvalue(thisObj->npp, NPNVWindowNPObject, &window);

// Get console object.
NPVariant consoleVar;
NPIdentifier id = npnfuncs->getstringidentifier("console");
npnfuncs->getproperty(thisObj->npp, window, id, &consoleVar);
NPObject* console = NPVARIANT_TO_OBJECT(consoleVar);

// Get the debug object.
id = npnfuncs->getstringidentifier("log");
//console.
// Invoke the call with the message!
NPVariant type;
STRINGZ_TO_NPVARIANT(message, type);
NPVariant args[] = { type };
NPVariant voidResponse;
bool didRun = npnfuncs->invoke(thisObj->npp, console, id, args, sizeof(args) / sizeof(args[0]), &voidResponse);
if (!didRun) assert(false);

// Cleanup all allocated objects, otherwise, reference count and
// memory leaks will happen.
npnfuncs->releaseobject(window);
npnfuncs->releasevariantvalue(&consoleVar);
npnfuncs->releasevariantvalue(&voidResponse);

Nothing is getting printed to the console, and neither is the assert failing. I'm not sure if there's a problem with my console.log statements as they don't print anything even when I use them with other javascript files. I want to use a statement like alert("Hello, world!") instead for the moment. I could modify my code to call functions of the form x.y(), but I don't understand how should I go about displaying an alert box. I used the tutorial at the following link. What should I do to display an alert box, called from the NPAPI DLL?

Edit: I am able to call the alert using it's window.alert("") form (X.Y() form), but this doesn't still solve my problem. I still don't understand how should I call a function of type X() directly from the NPAPI.

Upvotes: 0

Views: 1321

Answers (1)

Rahul Gulati
Rahul Gulati

Reputation: 363

Found it! I couldn't find a specific method to call a function of type X(). Instead, I was able to call it as window.X(), by placing the definition of function X() in the background.html page of the extension. So, if I created a function function myAlert(message){alert(message);} and placed it in background.html, I could make a call to window.myAlert(argument) from the NPAPI, and the above function would get called.

Upvotes: 0

Related Questions