Search code examples
javascriptc++qtqtwebkit

Cannot access Qt object methods through javascript using QtWebkit


Using QtWebkit's javascript bridge, I have created a class to interface the data in my web frame with the rest of my Qt code. it recognises the object, but none of its methods.

//executed with main window constructor
void MainWindow::initJavascriptInterface(){

    webInterfacer JSInterface;
    QWebFrame *frame = ui->webView->page()->mainFrame();
    frame->addToJavaScriptWindowObject("sender",&JSInterface);

}

The class has only one public slot called getInfo() (I know the name sucks but it's for testing, i have tried with different function names in case it was a collision).

webinterfacer.h

#ifndef WEBINTERFACER_H
#define WEBINTERFACER_H

#include <QObject>

class webInterfacer : public QObject
{

Q_OBJECT

public:
    explicit webInterfacer();
    ~webInterfacer();

public slots:
    void getInfo();

signals:
    //signal to emit when getInfo is called
    void openPopup(QString,QString);
};

#endif // WEBINTERFACER_H

I tried with different content in getInfo, even an empty function, it is never recognized.

In my HTML header (jQuery):

$(document).ready(function(){
    if(window.sender){
        alert("obj: " + typeof sender); //shows "obj: object"
        alert("getInfo: " + typeof sender.getInfo); //shows "getInfo: undefined"
    }
}

Solution

  • webInterFacer JSInterface; Your webInterfacer object is a local variable.It is destroyed as soon as it is out of scope ie, once you exit the function initJavaScriptInterface();

    Fix

    void MainWindow::initJavascriptInterface(){
    
    webInterfacer* JSInterface = new webInterfacer();
    QWebFrame *frame = ui->webView->page()->mainFrame();
    frame->addToJavaScriptWindowObject("sender",JSInterface);
    

    }