javascript - 如何使用 NPAPI 创建一个新的 JS 对象?

标签 javascript c++ npapi

我正在编写一个 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/

相关文章:

javascript - 如何让jquery停止执行1秒

javascript - 单击 React 组件外部时关闭菜单

c++ - 如何使用 ICU 将 UDate 从一个时区转换为另一个时区

c++ - 有截断吗?

c++ - 跨平台 NPAPI 接口(interface)/集成

javascript - 如何根据给定的过滤器返回并获取对象属性的总和?

javascript - jQuery Find 在 HTML 模板中找不到元素

c++ - Valgrind 声称我在使用 new 时使用 malloc

c++ - 在 NPAPI 中使用 VMR9 进行视频渲染

npapi - Edge 中 Chrome native 消息传递的等效项