我正在尝试将我的代码从QWebView迁移到QWebEngine。我想将代码中的对象添加到javascript中。在QWebView中,可以使用addToJavaScriptWindowObject函数。我们如何在QWebEngine中做到这一点。
webview-> page()-> mainFrame()-> addToJavaScriptWindowObject(“ qtObject”,this);
我们的Java脚本需要调用“ qtObject”函数。
答案 0 :(得分:0)
QFile webChannelJsFile(":/qtwebchannel/qwebchannel.js");
if (!webChannelJsFile.open(QIODevice::ReadOnly)) {
qDebug() << QString("Couldn't open qwebchannel.js file: %1").arg(webChannelJsFile.errorString());
}
else {
qDebug() << "OK webEngineProfile";
QByteArray webChannelJs = webChannelJsFile.readAll();
webChannelJs.append(
"\n"
"var qtObject"
"\n"
"new QWebChannel(qt.webChannelTransport, function(channel) {"
" qtObject = channel.objects.qtObject;"
"});"
);
QWebEngineScript script;
script.setName("qwebchannel.js");
script.setInjectionPoint(QWebEngineScript::DocumentCreation);
script.setRunsOnSubFrames(false);
script.setWorldId(QWebEngineScript::MainWorld);
script.setSourceCode(webChannelJs);
page->scripts().insert(script);
QWebChannel *channel = new QWebChannel(page);
channel->registerObject("qtObject", this);
page->setWebChannel(channel);
return page;