Search code examples
pluginssafarinpapi

NPAPI plug-in in safari can not call js function?


all.I want to call a js function to show something in my plugin.This is my code

NPObject* npwindow = NULL; 
NPError ret = browser->getvalue(mInstanceForJS, NPNVWindowNPObject, &npwindow); 
if (ret != NPERR_NO_ERROR) 
    return ; 
// Get window object. 
NPVariant windowVar; 
NPIdentifier winID = browser->getstringidentifier("window"); 
bool bRet = browser->getproperty(mInstanceForJS, npwindow, winID, &windowVar); 
if (!bRet) 
{ 
    browser->releaseobject(npwindow); 
    return ; 
}
NPObject* window = NPVARIANT_TO_OBJECT(windowVar);
NPVariant voidResponse;

NPVariant elementId;
STRINGZ_TO_NPVARIANT([info UTF8String], elementId);
NPVariant args[] = {elementId};

NPIdentifier funcID= browser->getstringidentifier([funName UTF8String]);
bRet = browser->invoke(mInstanceForJS, window, funcID, args, 1, &voidResponse);
browser->releasevariantvalue(&windowVar);

when called bRet = browser->invoke(mInstanceForJS, window, funcID, args, 1, &voidResponse);,Safari can not responsed.Is there any errors?


Solution

  • npwindow is already the window object; you're effectively querying for "window.window". Granted, I don't know why this wouldn't work, but it seems a little weird.

    That's problem #1.

    Problem #2 is that you're using STRINGZ_TO_NPVARIANT to store the result of UTF8String. STRINGZ_TO_NPVARIANT doesn't copy the memory, so you could be in trouble if the function wanted to hang onto that string, since the string returned by that will be freed when your autorelease pool cycles. Of course, that could also be a memory leak. Either way, the correct way to pass a string to the browser is to allocate memory for it using NPN_MemAlloc and then copy the string in. Then pass that pointer to the browser. See http://npapi.com/memory for more info.

    Problem #3 is that you haven't given us any idea of when you are running this code; it's quite possible that you are trying to run this code too early in the plugin or page lifecycle and thus it may not work because of that.

    Then there is another question: What do you mean by "Safari can no responsed"? Forgetting the grammatical error, I'm not sure what you mean by this. Does it hang? is bRet false? Does your computer suddenly get encased in ice, thus halting all processing? If the above is not helpful, please answer these questions and I'll try again.