我使用QT WebEngine框架来显示网页。我在页面加载时将javascript注入其中,并希望允许javascript能够访问QT对象。显然,要做到这一点,必须存在一个QWebChannel,它可以在C( javascript)和我的C++/QT项目的其余部分之间建立一些IPC。我遇到了QWebEnginePage::setWebChannel (QWebChannel *channel)函数,但是我找不到使用它的任何例子。文档(http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel)提到,qt.webChannelTransport应该在javascript上下文中可用,但我不知道在qwebchannel.js (https://github.com/qtproject/qtwebchannel/blob/dev/src/webchannel/qwebchannel.js)中是在哪里建立的。我已经看过WebChannel示例(http://doc.qt.io/qt-5/qtwebchannel-examples.html),如果可能的话,我希望避免使用WebSockets。
下面是我如何尝试实现网络频道。
每当加载页面时,我都会建立一个通道,并在C++:中注入javascript
QWebChannel *channel = new QWebChannel();
channel->registerObject(QStringLiteral("jshelper"), helper);
view->page()->runJavaScript(qwebjs); //this is qwebchannel.js
view->page()->setWebChannel(channel);
view->page()->runJavaScript(myfunction); //function that calls QT object (jshelper)In Javascript:
new QWebChannel(qt.webChannelTransport, function(channel) { ... });这会导致通道连接不正确(假设这是因为qt.webChannelTransport,因为我使用WebSockets时它正在工作)。任何指向用QWebChannel以这种方式设置QWebEnginePage的例子的指针也是值得赞赏的。
发布于 2015-08-12 13:29:58
简短回答:将<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>添加到html页面(当然,在调用new QWebChannel之前),并从C++代码中删除view->page()->runJavaScript(qwebjs); //this is qwebchannel.js行。
长答案:
我也遇到了很多麻烦,弄清楚如何正确使用QWebChannel而没有WebSockets --在QT5.5源代码和邮件列表中翻遍之后,我设法让它正常工作(仍然缺乏文档)。注意,只适用于 the new Qt 5.5。
下面是如何使用QWebChannel:
// file: MyWebEngineView.cpp, MyWebEngineView extends QWebEngineView
QWebChannel *channel = new QWebChannel(page());
// set the web channel to be used by the page
// see http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel
page()->setWebChannel(channel);
// register QObjects to be exposed to JavaScript
channel->registerObject(QStringLiteral("jshelper"), helper);
// now you can call page()->runJavaScript(...) etc
// you DON'T need to call runJavaScript with qwebchannel.js, see the html file below
// load your page
load(url);在JS方面:
<!-- NOTE: this is what you're missing -->
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
<!-- it's a good idea to initialize webchannel after DOM ready, if your code is going to manipulate the DOM -->
document.addEventListener("DOMContentLoaded", function () {
new QWebChannel(qt.webChannelTransport, function (channel) {
var jshelper = channel.objects.jshelper;
// do what you gotta do
});
});
</script>还要确保您已经将QT += webenginewidgets webchannel添加到您的.pro文件中,否则不会生成!
奖金:,您现在可以从Chrome工具中调试您的JavaScript了!只需在Qt代码中添加以下内容(最好是在应用程序启动时):
#ifdef QT_DEBUG
qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "23654");
#endif然后启动应用程序,导航到Chrome中的http://localhost:23654,您将得到一个功能齐全的JS调试器、分析器、控制台等:)
跟踪(19/04/2016):如果远程调试器无法工作,请注意,在调用QWebEngineSettings或任何其他与WebEngine相关的类之前,还必须发生qputenv调用,因为这些调用会立即触发WebEngine“合子”进程(合子是所有未来QtWebEngineProcesses分叉的父QtWebEngineProcess ),而qputenv则无法影响它。花了几个小时追踪这个。
https://stackoverflow.com/questions/31928444
复制相似问题