1 . 如何在NPClass中存储自己的自定义数据?
只要实现NPClass的allocate和deallocate两个方法,并定义自己的扩展NPClass结构便可
static struct NPClass nativeScriptablePluginClass = {
NP_CLASS_STRUCT_VERSION,
JSCLASS_alloc,
JSCLASS_free,
NULL,
JSCLASS_hasMethod,
JSCLASS_invoke,
NULL,
JSCLASS_hasProperty,
JSCLASS_getProperty,
NULL,
NULL,
};
//定义自己的扩展结构体
typedef struct MyScriptPluginClass MyScriptPluginClass;
struct MyScriptPluginClass {
NPClass nativeClass;
NPUTF8 *someStringData; //这是我们的自定义数据
};
//在自定义的alloc方法中返回为自定义NPClass申请的内存
NPObject* JSCLASS_alloc(NPP inst, NPClass *aClass) {
return (NPObject *)malloc(sizeof(struct MyScriptPluginClass));
}
//相应的释放
void JSCLASS_free(NPObject *nobj) {
//之后都可以通过种类型强转得到我们自定义的结构体
MyScriptPluginClass *obj = (MyScriptPluginClass *)nobj;
free(obj->someStringData);
free(obj);
}
2 . 如何在插件中调用页面中的js方法?
//这里我们将实现一个可以调用window.eval的方法
void JSAPI_methodImpl_getLocation(NPObject *o) {
NPString rt;
MyScriptPluginClass *obj = (MyScriptPluginClass *)o;
NPP _npp = obj->instance;
NPObject *window = NULL;
//static NPNetscapeFuncs* browser;
//获取window对象
browser->getvalue(_npp, NPNVWindowNPObject, &window);
NPIdentifier eval = browser->getstringidentifier("eval");
NPVariant evalResponse;
NPVariant evalCode;
//初始化我们需要eval的代码
char *c_javascriptCode = calloc(2048, 1);
sprintf(c_javascriptCode, "(function(){"
"return window.location.href;\n"
"})();");
STRINGZ_TO_NPVARIANT(c_javascriptCode, evalCode);
NPVariant args[] = {evalCode};
//window.eval(mycode);
browser->invoke(_npp, window, eval, args, 1, &evalResponse);
free(c_javascriptCode);
//判断一下js的返回值是否为我们期望的字符串类型
if (NPVARIANT_IS_STRING(evalResponse)) {
//得到我们想要的返回值
rt = NPVARIANT_TO_STRING(evalResponse);
fprintf(stdout, "window.location = %.*s", rt.UTF8Length, rt.UTF8Characters);
}
browser->releaseobject(window);
browser->releasevariantvalue(&evalResponse);
}
3 . 如何管理内存
http://colonelpanic.net/2009/12/memory-management-in-npapi/
[...] 原帖 http://bluehua.org/2012/04/03/1839.html No related posts. [...]