最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

I have a web page loaded in a QWebView. In there, I would like to have JavaScript call a function of my application. That function would then returns some strings that JavaScript would dynamically display.

Can it be done using QWebView? Basically, is it possible to have some bridge between the application (in C++) and the QWebView control?

I have a web page loaded in a QWebView. In there, I would like to have JavaScript call a function of my application. That function would then returns some strings that JavaScript would dynamically display.

Can it be done using QWebView? Basically, is it possible to have some bridge between the application (in C++) and the QWebView control?

Share Improve this question edited May 4, 2012 at 8:32 Luc Touraille 82.1k16 gold badges99 silver badges139 bronze badges asked Mar 8, 2012 at 9:15 laurentlaurent 90.8k82 gold badges309 silver badges441 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

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");
发布评论

评论列表(0)

  1. 暂无评论