是否可以从QWebView中的JavaScript调用C ++函数? [英] Is it possible to call a C++ function from JavaScript in a QWebView?
问题描述
我有一个网页加载在QWebView。在那里,我想有一个JavaScript调用我的应用程序的函数。该函数将返回JavaScript将动态显示的一些字符串。
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.
可以使用QWebView吗?基本上,是否可能在应用程序(在C ++中)和QWebView控件之间有一些桥梁?
Can it be done using QWebView? Basically, is it possible to have some bridge between the application (in C++) and the QWebView control?
推荐答案
最终做到了。我在我的头文件中用 Q_INVOKABLE
方法声明了一个JavaScriptBridge类。 Q_INVOKABLE
方法可以从JavaScript调用:
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_;
};
然后在我的.cpp文件中创建桥:
Then in my .cpp file, I create the bridge:
jsBridge_ = new DictionaryJavaScriptBridge(this);
我听到 javaScriptWindowObjectCleared
信号。这一步很重要,因为WebKit将在加载新页面时清除所有JavaScript对象,因此您需要每次都添加回桥:
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()));
最后,在 javaScriptWindowObjectCleared
添加JavaScript桥:
Finally, in the javaScriptWindowObjectCleared
slot, I add the JavaScript bridge:
void DictionaryWidget::mainFrame_javaScriptWindowObjectCleared() {
ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("ehbridge", jsBridge_);
}
现在从JavaScript开始,会出现一个全局的ehbridge对象。我可以像一个普通的JavaScript对象(Qt将Qt的类型转换为JavaScript类型)来调用它的方法。
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");
这篇关于是否可以从QWebView中的JavaScript调用C ++函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!