【发布时间】:2018-01-19 03:23:11
【问题描述】:
我正在使用 QT 5.9 WebEngine 框架来显示网页。我在加载时将 javascript 注入页面,并希望允许 javascript 能够访问 QT 对象。
我在 JS 中调用了 QWebchannel 回调,但对象方法和属性未定义。
注意:我需要注入所有的 JS 代码,并且不能更改加载页面的 html 代码。这意味着我不能包含任何 js 脚本,也不能直接在 html 页面中编写任何 js 代码。
这是我的代码:
我使用配置文件创建 QWebEnginePage 对象并注入 JS 文件,如下所示:
// file: webview.cpp, webview extends **QWebEngineView**
QWebEngineScript script;
script.setSourceCode(qwebchannelsource); // source is qwebchannel.js
script.setInjectionPoint(QWebEngineScript::DocumentCreation);
profile->scripts()->insert(script);
QWebEnginePage page* = new QWebEnginePage(profile, this);
QWebChannel *channel = new QWebChannel(page);
page->setWebChannel(channel);
channel->registerObject(QStringLiteral("jshelper"), &JSHelper::instance());
JSHelper
class JSHelper : public QObject
{
public:
static JSHelper &instance();
QString someString;
int someInt;
Q_INVOKABLE int getInt();
Q_PROPERTY(int myIntInCppSide READ getInt)
private:
JSHelper();
};
JS代码
// also injected into the page (like qwebchannel.js) at QWebEngineScript::DocumentReady
new QWebChannel(qt.webChannelTransport, function (channel) {
var jshelper = channel.objects.jshelper;
console.warn('qwebchannel triggered');
// do what you gotta do
if (jshelper === undefined) {
console.warn("jshelper is undefined");
}
else {
console.warn("jshelper is awesome");
}
console.warn("jshelper value of string " + jshelper.somestring);
console.warn("jshelper value of int " + jshelper.myIntInCppSide);
jshelper.myIntInCppSide(function (n) {
console.warn("jshelper value of int " + n);
});
});
我的输出:
qwebchannel triggered"
jshelper is awesome"
jshelper value of string undefined"
jshelper value of int undefined"
Uncaught TypeError: jshelper.myIntInCppSide is not a function"
如您所见,我已经从几个答案中尝试了各种建议,但似乎没有什么能解决我的问题,即该功能不存在。 即使使用远程调试,我也可以看到 jshelper 是 QObject 类型,但它没有我的类的属性和方法。
QT QWebEnginePage::setWebChannel() transport object
Undefined properties and return types when using QWebChannel
【问题讨论】:
-
您是否尝试在
JSHelpre类声明的开头插入Q_OBJECT宏? -
是的,我得到“未定义的对 JSHelper 的 vtable 的引用”编译错误
-
啊,我错过了你有默认构造函数私有的事实,这一定是编译错误的原因。如果你公开默认构造函数并使用
Q_OBJECT宏,你能检查一下会发生什么吗? -
谢谢!我头疼了 2 天,没有得到关于在任何地方设置 Q_OBJECT 宏的信息。公开类构造函数并添加宏解决了我的问题
-
很高兴它有帮助。将其发布为答案,您介意接受吗? )
标签: qt qtwebengine