Qt WebChannel JavaScript API

设置 JavaScript API

要通信与 QWebChannel or WebChannel ,客户端必须使用和设置 JavaScript API 提供通过 qwebchannel.js 。若客户端运行在 Qt WebEngine ,可以加载文件通过 qrc:///qtwebchannel/qwebchannel.js 。对于外部客户端,需要将文件拷贝到 Web 服务器。 然后实例化 QWebChannel 对象,并向其传递传输对象和回调函数,一旦通道初始化完成且已发布对象变为可用时,其就会被援引。

传输对象实现最少消息传递接口。它应是对象且具有 send() 函数,其接受字符串化 JSON 消息,并将消息传输到服务器侧 QWebChannelAbstractTransport 对象。此外,它的 onmessage 特性应被调用,当从自服务器收到消息时。另外,可以使用 WebSocket 去实现接口。

注意:JavaScript QWebChannel 对象应该被构造一旦传输对象可完整操作。对于 WebSocket,意味着应该创建 QWebChannel 在套接字的 onopen 处理程序。查看 Qt WebChannel 独立范例 看如何做到这点。

与 QObject 交互

一旦被递给 QWebChannel object's callback is invoked, the channel has finished initialization and all published objects are accessible to the HTML client via the channel.objects 特性。因此,假定采用标识符 foo 发布对象,然后可以与它交互,如以下范例所示。注意,HTML 客户端和 QML/C++ 服务器之间的所有通信都是异步的。特性被缓存在 HTML 侧。此外,请记住仅可以转换为 JSON 的 QML/C++ 数据类型能被正确 (反) 序列化,因此 HTML 客户端可以访问。

new QWebChannel(yourTransport, function(channel) {
    // Connect to a signal:
    channel.objects.foo.mySignal.connect(function() {
        // This callback will be invoked whenever the signal is emitted on the C++/QML side.
        console.log(arguments);
    });
    // To make the object known globally, assign it to the window object, i.e.:
    window.foo = channel.objects.foo;
    // Invoke a method:
    foo.myMethod(arg1, arg2, function(returnValue) {
        // This callback will be invoked when myMethod has a return value. Keep in mind that
        // the communication is asynchronous, hence the need for this callback.
        console.log(returnValue);
    });
    // Read a property value, which is cached on the client side:
    console.log(foo.myProperty);
    // Writing a property will instantly update the client side cache.
    // The remote end will be notified about the change asynchronously
    foo.myProperty = "Hello World!";
    // To get notified about remote property changes,
    // simply connect to the corresponding notify signal:
    foo.onMyPropertyChanged.connect(function(newValue) {
        console.log(newValue);
    });
    // One can also access enums that are marked with Q_ENUM:
    console.log(foo.MyEnum.MyEnumerator);
});