Is it possible to call a C++ function from JavaScript in a QWebView?

别等时光非礼了梦想. 提交于 2019-12-03 05:38:44

This is how I ended up doing it. I declared a "JavaScriptBridge" class in my header file with a Q_INVOKABLE method. Q_INVOKABLE methods can be called from JavaScript:

class DictionaryJavaScriptBridge : public QObject {

    Q_OBJECT

public:

    DictionaryJavaScriptBridge(DictionaryWidget* dictionaryWidget); 
    Q_INVOKABLE QStringList sentences(QString characters);

private:

    DictionaryWidget* dictionaryWidget_;

};

Then in my .cpp file, I create the bridge:

jsBridge_ = new DictionaryJavaScriptBridge(this);

And I listen to the javaScriptWindowObjectCleared signal. This step is important because WebKit is going to clear all the JavaScript objects when loading a new page, so you need to add back the bridge every time:

connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(mainFrame_javaScriptWindowObjectCleared()));

Finally, in the javaScriptWindowObjectCleared slot, I add the JavaScript bridge:

void DictionaryWidget::mainFrame_javaScriptWindowObjectCleared() {
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("ehbridge", jsBridge_);
}

Now from JavaScript, there will be a global "ehbridge" object exposed. I can call its methods like a normal JavaScript object (Qt converts Qt's types to JavaScript types)

var sentences = ehbridge.sentences("test");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!