Return Array from NPAPI plugin to java script

前端 未结 1 1337
故里飘歌
故里飘歌 2021-01-03 10:18

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 a
1条回答
  •  时光说笑
    2021-01-03 10:43

    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:

    1. Get the NPObject for the window (sounds like you have this)
    2. Create a new array and get the NPObject for that array
    3. Invoke "push" on that NPObject for each item you want to send to the DOM
    4. 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::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

    0 讨论(0)
提交回复
热议问题