问题
I want to return array of string from NPAPI plugin to Javascript. Currently I am using only plain NPAPI. I have read the following links:
- NPVariant to string array
- http://www.m0interactive.com/archives/2010/10/21/how_to_communicate_back_to_javascript_from_npapi_plugin.html
I am able to return alert() from plugin to javascript and I can get the NPNVWindowObject, but I am stuck right now on figuring out how to push elements onto the array and return it to javascript.
Working code samples would be appreciated, thanks
回答1:
You're already close; you just need to fill in a few details. The FireBreath codebase has examples of doing this, but the actual implementation is a bit abstracted. I don't have any raw NPAPI code that does this; I build plugins in FireBreath and it's almost ridiculously simple there. I can tell you what you need to do, however.
The problem gets simpler if you break it down into a few steps:
- Get the NPObject for the window (sounds like you have this)
- Create a new array and get the NPObject for that array
- Invoke "push" on that NPObject for each item you want to send to the DOM
- Retain the NPObject for the array and return it in the return value NPVariant
I'll take a stab at the code you'd use for these; there might be some minor errors.
1) Get the NPObject for the window
// Get window object.
NPObject* window = NULL;
NPN_GetValue(npp_, NPNVWindowNPObject, &window);
// Remember that when we're done we need to NPN_ReleaseObject the window!
2) Create a new array and get the NPObject for that array
Basically we do this by calling window.Array(), which you do by invoking Array on the window.
// Get the array object
NPObject* array = NULL;
NPVariant arrayVar;
NPN_Invoke(_npp, window, NPN_GetStringIdentifier("Array"), NULL, 0, &arrayVar);
array = arrayVar.value.objectValue;
// Note that we don't release the arrayVar because we'll be holding onto the pointer and returning it later
3) Invoke "push" on that NPObject for each item you want to send to the DOM
NPIdentifier pushId = NPN_GetStringIdentifier("push");
for (std::vector<std::string>::iterator it = stringList.begin(); it != stringList.end(); ++it) {
NPVariant argToPush;
NPVariant res;
STRINGN_TO_NPVARIANT(it->c_str(), it->size(), argToPush);
NPN_Invoke(_npp, array, pushId, &argToPush, 1, &res);
// Discard the result
NPN_ReleaseVariantValue(&res);
}
4) Retain the NPObject for the array and return it in the return value NPVariant
// Actually we don't need to retain the NPObject; we just won't release it. Same thing.
OBJECT_TO_NPVARIANT(array, *retVal);
// We're assuming that the NPVariant* param passed into this function is called retVal
That should pretty much do it. Make sure you understand how memory management works; read http://npapi.com/memory if you haven't.
Good luck
来源:https://stackoverflow.com/questions/12078250/return-array-from-npapi-plugin-to-java-script