What I try to do is to call back to the embedding browser c/c++ function
from javascript in a web page
in order to achieve some kind of notifications.

By following the jsapi pattern such as jsbool.c, I implemented an
notification object and registered it
at runtime as a global object. I expect the object acts like a native object
in js such as Boolean.
In a web page, I have javascript to instantiate the object and call on its
method.
However, I haven't succeeded yet.

The followings are the simplified code segments:

(1). c/c++ code embedded in the browser app:

/*notification object*/
static JSBool
jscallback_Notify(JSContext *cx, JSObject *obj, uintN argc, jsval *argv,
jsval *rval)
{
    FILE *fp = fopen("jsbc.txt", "a+");
 if(fp)
 {
        fprintf(fp, "jscallback gets called\n");
        fclose(fp);
 }

    return JS_TRUE;
}

static JSFunctionSpec jscallback_functions[] = {
    {"Notify", jscallback_Notify, 0, 0, 0},
    {0, 0, 0, 0, 0}
};

static JSClass jscallback_class = {
    "JSCB", 0,
    JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,
    JS_EnumerateStub, JS_ResolveStub,   JS_ConvertStub,   JS_FinalizeStub
};

static JSBool
JSCB(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
 return JS_TRUE;
}

/*creat, register and initialise*/
    nsCOMPtr<nsIJSRuntimeService> rtsvc =
  do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv);
    if(NS_FAILED(rv) || NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt)
        goto clean;

    jscontext = JS_NewContext(rt, 1000);
    if(!jscontext)
        goto clean;

    xpc = do_GetService(nsIXPConnect::GetCID(), &rv);
    if(NS_FAILED(rv) || !xpc)
        goto clean;

    cxstack = do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
    if(NS_FAILED(rv))
        goto clean;

    if(NS_FAILED(cxstack->Push(jscontext)))
        goto clean;

    jscb = JS_NewObject(jscontext, &jscallback_class, NULL, NULL);
    if(!jscb)
        goto clean;

    if(!JS_InitStandardClasses(jscontext, jscb))
        goto clean;

    if(!JS_DefineFunctions(jscontext, jscb, jscallback_functions))
        goto clean;

//    if(NS_FAILED(xpc->InitClasses(jscontext, jscb)))

    if(!JS_InitClass(jscontext, jscb, NULL, &jscallback_class, JSCB,
              0, NULL, jscallback_functions, NULL, NULL))
        goto clean;


(2). javascript in the web page

<script language="javascript">
function test_notif()
{
    var t = new JSCB();
    t.Notify();
}
</script>

<body onload="test_notif()">
</body>


However, the file defined in the jscallback_Notify method was never created.
In the other words, the object hasn't been created properly. I don't know
what I missed out so far. I didn't use xpconnect here to avoid loading
module,
createinstance such procedures. I may be wrong. Any suggestion welcomed.

Thanks.




Reply via email to