Search code examples
javascriptqtfirefox-addon

How to establish a realtime communcation from a browser extension to qt


I'm working on a firefox extension which requires a real-time connectivity between the system side software and web.

I mean, I want something like this

in extension

var observer = new MutationObserver(function(childList){sendToQt(JSON.stringify(childList))})
observer.observe(myElement,{childList:true})

in qt application.

public signals:
    void messageReceived(QString message)

connect(myobject, &MyClass::messageReceived,this,&ThisClass::logMessage)
void logMessage(QString message){
    std::cout<<message.toStdString()<<endl;
    sendMessageBack(recieved)
}

When a mutation observed by mutation observer initialized with extension, it has to be send to qt as a string message and response from qt to extension. I am much familiar with python sockets. But it seems that it's not gonna work with such a project. Basically it's by first firefox extension build and I am not much familiar with facilities provided by firefox for an extension. Is there any such technology which establishes a real-time communication between qt and my extensions.


Solution

  • Easy IPC using what both Qt and Browser extensions support:

    • Websockets: Simple, bidirectional, you can pass JSON around
    • A local HTTP/S API: A bit more fancy and structured, possibly more cumbersome if you just want local IPC

    WebSocket

    1. Qt: Create a QWebSocketServer in your Qt application, and connect to the usual signal. See Qt WebSocket example from the "Echo Server" for an actual example.
    2. Qt: Use QJson for encoding and decoding
    3. Firefox extension: Create a new WebSocket(<url>) in your Firefox extension, and connect to locahost on the port/path you defined in your Qt app. Here is a Sample extension using WebSockets for Firefox
    4. Communicate happily between the two!

    HTTP/S API

    You get the idea, in this case you use third party library like Mangoose, RESTinio, or CppRestSDK.

    A couple open source Qt alternatives exist as well for convenience, but will likely the maturity of other projects. And the Qt official HTTP server isn't in the mainline Qt 5 versions AFAIK.