QWebEngine 和 QWebChannel:传输对象 `qt.webChannelTransport` 在页面重新加载后消失

QWebEngine & QWebChannel: transport object `qt.webChannelTransport` disappeared after page reload

我在我的应用程序和 WebEngine 之间创建了网络通道,以便在 JavaScript 的网络端公开 QObject 但通道在页面重新加载后丢失,或者如果我点击 link 到另一个页面。

我想我需要在页面重新加载时重新创建频道,但我没能成功。我尝试在页面加载、进度和完成的插槽上执行此操作,但只得到 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";
}

频道是在页面端使用 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>

示例的完整代码在这里:https://github.com/DanmerZ/QWebChannels-example

视频:https://monosnap.com/file/ZTOgj1QH06VRVF3ogmXln07eOVXXCW

P.S。此错误仅针对Qt5.7,我检查了Qt5.6.1,通道正常。 https://bugreports.qt.io/browse/QTBUG-52209?jql=text%20~%20%22QWebChannel%20reload%22

是个bug,Qt5.7.1会修复,请看https://bugreports.qt.io/browse/QTBUG-53411 and http://code.qt.io/cgit/qt/qtwebengine.git/commit/?h=dev&id=ca6762abde85fe3104ec4f064b85319474ba2deb