XPCOM: Javascript function call
Mozilla May 26th, 2007
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.
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:
- XPCOM: Javascript function call alternative
- XPCOM array
- 一个 JavaScript 代码语法高亮类
- Creating a simple C++ component
Tags: JavaScript, xpcom
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?
Do you have all the code?
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
I am having the problem as John encountered, I can only see “undefined” on the JavaScript alert box”. Does anyone have idea why?
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
I am frequently searching for brandnew articles in the internet about this topic. Thx!!