Sometimes we need to call javascript function form a c++ xpcom. The following is a method for this.

1. Define your javascript callback interface in a IDL file.

1
2
3
interface JSCallback : nsISupports {
    boolean call(in PRUint32 bogus, in PRUint32 aData);
}

And another interface looks like:

1
2
3
interface TestJSCallback : nsISupports {
    void sum(in PRUint32 first, in PRUint32 second, in JSCallBack aCallback);
}

2. Complete the sum function’s cpp code.

1
2
3
4
5
6
7
8
NS_IMETHODIMP TestJSCallback::Sum(PRUint32 first, PRUint32 second, JSCallback *aCallback) {
    PRBool ret = true;
    nsCOMPtr<JSCallback> js_callback = aCallback;
 
    js_callback->Call(0, first+second, &ret);
 
    return NS_OK;
}

3. Interface call.

?View Code JAVASCRIPT
1
2
3
4
5
6
var test = function(sum) {
    alert(sum);
};
 
var com = Components.classes["XXXXXX"].getService(Components.interfaces.TestJSCallback);
com.sum(1, 2, test);

It will pop up a dialog shows “3″ … Cheers…

Related posts:

  1. XPCOM: Javascript function call alternative
  2. XPCOM array
  3. 一个 JavaScript 代码语法高亮类
  4. Creating a simple C++ component

Tags: ,



Reader's Comments

  1. John SWITZERLAND | 2007-07-25 at 2.49 pm

    thanks for the tip, that’s really smart. I’m now able to trig a js function from my c++ xpcom component. The only bug is that the parameter given to the callback are not correctly handled, ie they appears as ‘undefined’ in the js function. Any idea?

    Reply to this comment
  2. Santa UNITED STATES | 2008-02-16 at 2.30 am

    Do you have all the code?

    Reply to this comment
  3. kid.duo CHINA | 2008-02-16 at 2.39 am

    You can check out the Firetray’s source code from google code.
    Or browse it online via http://code.google.com/p/firetray/source/browse

    Reply to this comment
  4. Dino UNITED STATES Windows XP Mozilla Firefox 3.0.6 | 2009-03-19 at 9.11 am

    I am having the problem as John encountered, I can only see “undefined” on the JavaScript alert box”. Does anyone have idea why?

    Reply to this comment
  5. Duo CHINA Windows XP Mozilla Firefox 3.0.7 | 2009-03-19 at 10.11 am

    I think you can take a look at minimizetotray’s source code, this is a extension works on Windows.

    The JavaScript callback is “window.extensions.mook.minimizetotray .trayCallback
    And it use following bind the callback function
    this.m_windowHider.minimize(baseWindows.length, baseWindows, null, this.trayCallback);
    This is the IDL define
    And you can look the minimize function detail

    Hope these helpful :)

    Reply to this comment
  6. Lypetepaymn CZECH REPUBLIC Windows XP Internet Explorer 6.0 | 2009-12-12 at 6.48 am

    I am frequently searching for brandnew articles in the internet about this topic. Thx!!

    Reply to this comment

Leave a Comment