我正在编写一个 NPAPI 插件。在 C++ 代码中,我无法使用 NPAPI 创建 JS 对象。我试过这个方法:
Foo.js
function Foo(p)
{
this.a=p;
}
Foo.prototype.get=function()
{
return this.a;
}
C++代码(我想创建Foo对象。只需链接我们在JS中可以做的事情。var s=new Foo(2);)
int newJSObject(const NPP instance,const NPNetscapeFuncs* npnfuncs,const string objectName,
const NPVariant* args,const int argsCount,NPVariant& result)
{
int status;
NPObject *winobj;
npnfuncs->getvalue(instance,NPNVWindowNPObject,&winobj);
NPVariant npJS;
NPIdentifier npJSId=npnfuncs->getstringidentifier(objectName.c_str());
status=npnfuncs->getproperty(instance,winobj,npJSId,&npJS);
NPObject* npObjJS = NPVARIANT_TO_OBJECT(npJS);
NPVariant npPrototype;
NPIdentifier npPrototypeId=npnfuncs->getstringidentifier("prototype");
status=npnfuncs->getproperty(instance,npObjJS,npPrototypeId,&npPrototype);
NPObject* npObjPrototype = NPVARIANT_TO_OBJECT(npPrototype);
NPVariant npJSConstructor;
NPIdentifier npJSConstructorId=npnfuncs->getstringidentifier("constructor");
status=npnfuncs->invoke(instance,npObjPrototype,npJSConstructorId,
args,argsCount,&npJSConstructor);
/*
* destroy memory
* */
npnfuncs->releaseobject(winobj);
npnfuncs->releasevariantvalue(&npJS);
npnfuncs->releasevariantvalue(&npJSConstructor);
result=npJS;
return status;
}
NPVariant jsFoo1;
NPVariant arg;
DOUBLE_TO_NPVARIANT(2,arg);
NPVariant prams[]={arg};
newJSObject(instance,npnfuncs,"Foo",prams,sizeof(prams)/sizeof(prams[0]),jsFoo);
NPVariant jsFoo2;
NPVariant arg;
DOUBLE_TO_NPVARIANT(3,arg);
NPVariant prams[]={arg};
newJSObject(instance,npnfuncs,"Foo",prams,sizeof(prams)/sizeof(prams[0]),jsFoo);
但是如果我们将jsFoo1和jsFoo2返回给JS代码,那么我们调用Fooxxx.get()。 jsFoo1 和 jsFoo2 都是 3。 我知道问题出在“构造函数”
谁能给我另一种使用 NPAPI 在 C++ 中创建 JS 对象的方法?
最佳答案
NPN_Construct 似乎不适用于浏览器对象,因此没有直接的方法来执行您想要的操作。但是,您可以做的是创建一个 javascript 函数来为您创建对象并返回它;您甚至可以使用 NPN_Evaluate 将其自动注入(inject)页面。
像这样:
function __create_object_2_params(obj, param1, param2) {
return new obj(param1, param2);
}
FireBreath在某些地方使用了一些类似的技巧。
关于javascript - 如何使用 NPAPI 创建一个新的 JS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838567/