问题
I created the web channel between my application and WebEngine
in order to have exposed QObject
on web side in JavaScript but the channel are lost after page reloading or in case if I click link to another page.
I think I need to recreate the channel on page reload but I didn't manage to do it. I tried to do it on page load, progress and finished slots but only got js: Uncaught ReferenceError: qt is not defined
.
<!-- language: lang-cpp -->
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->webEngineWidget->load(QUrl("qrc:/index.html"));
page = ui->webEngineWidget->page();
channel = new QWebChannel;
channel->registerObject("external", &exposedObject);
page->setWebChannel(channel);
connect(page, &QWebEnginePage::loadStarted, this, &MainWindow::onPageLoadStarted);
connect(page, &QWebEnginePage::loadProgress, this, &MainWindow::onPageLoadProgress);
connect(page, &QWebEnginePage::loadFinished, this, &MainWindow::onPageLoadFinished);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onPageLoadStarted()
{
qDebug() << "Loading started";
}
void MainWindow::onPageLoadProgress(int progress)
{
qDebug() << "Loading in progress: " << progress;
}
void MainWindow::onPageLoadFinished()
{
qDebug() << "Loading finished";
}
Channel is created on the page side using qwebchannel.js
:
<h1>Page</h1>
<a href="other.html">Other Page</a>
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script>
var webChannel = new QWebChannel(qt.webChannelTransport, function(channel){
window.external = channel.objects.external;
});
</script>
Full code of the example is here: https://github.com/DanmerZ/QWebChannels-example
Video: https://monosnap.com/file/ZTOgj1QH06VRVF3ogmXln07eOVXXCW
P.S. This error is only for Qt5.7, I checked Qt5.6.1 and the channel works just fine. https://bugreports.qt.io/browse/QTBUG-52209?jql=text%20~%20%22QWebChannel%20reload%22
回答1:
It is a bug, fix will be in Qt5.7.1, please see https://bugreports.qt.io/browse/QTBUG-53411 and http://code.qt.io/cgit/qt/qtwebengine.git/commit/?h=dev&id=ca6762abde85fe3104ec4f064b85319474ba2deb
来源:https://stackoverflow.com/questions/38394130/qwebengine-qwebchannel-transport-object-qt-webchanneltransport-disappeared