I have wrote a blog post about how to call JavaScript function from C++ XPCOM (XPCOM: Javascript function call), but just found another way to achieve this goal by observer mechanism.

C++ XPCOM code:

1
2
nsCOMPtr<nsIObserverService> observerService = do_GetService("@mozilla.org/observer-service;1");
observerService->NotifyObservers(NULL, "ping", ToNewUnicode(NS_ConvertASCIItoUTF16("www.google.com")));

JavaScript code:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const Cc = Components.classes;
const Ci = Components.interfaces;
 
var aObserver = { 
    observe: function(subject, topic, data) {
        if (topic == "ping") {
            alert("Ping: " + data);
        }   
    }   
};
 
var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
 
observerService.addObserver(aObserver, "ping", false);

In multithreading XPCOM, sometime we should call JavaScript function by nsIProxyObjectManager (JavaScript and UI are on a single thread, see nsISupports proxies and nsProxiedService.h for detail)

Related posts:

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

Tags: ,



Leave a Comment