从Webviews Javascript调用C++方法

dus*_*n.b 3 qtwebkit webview qml qt5

在qt4 qml qtwebkit 1.0中,组件webview具有一个属性javaScriptWindowObjects.我用它将javaScriptWindowObjects添加到我的webpages javascript的上下文中来调用c ++函数.像这样

WebView{
    url: "http://test.com"
    anchors.fill: parent
    scale: 1.0

    javaScriptWindowObjects: QtObject {
        WebView.windowObjectName: "native"

        function foo(x, y) {
             console.log("This is a call from javascript");
             myCppHandler.fooNative(b,c);
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我可以从网页javascript中调用它

<script type="text/javascript">
    native.foo(1,2)
</script>
Run Code Online (Sandbox Code Playgroud)

但是在qt5 qml qtwebkit 3.0中没有这样的东西 javaScriptWindowObjects

我怎样才能在qt5 qml中实现这一目标?

dus*_*n.b 6

只是为了完成这项工作的记录:

import QtQuick 2.0
import QtWebKit 3.0
import QtWebKit.experimental 1.0

Rectangle {

   width: 1024
   height: 768

   WebView{
       url: "http://localhost"
       anchors.fill: parent

       experimental.preferences.navigatorQtObjectEnabled: true
       experimental.onMessageReceived: {

           console.debug("get msg from javascript")
           experimental.postMessage("HELLO")
       }
   } // webview
} // rectanlge


<html>
<body>
<h1>It just works!</h1>

<p>Play with me...</p>

<button onclick="nativecall();">test</button>
<div id="out"></div>

<script type="text/javascript">
    function nativecall(){
        console.log("will try native call");
        var elem = document.getElementById("out").innerHTML="clicked";
        navigator.qt.postMessage('this is a js call');
    }

    function jsCall(message){
        var elem = document.getElementById("out").innerHTML="and the other way around " + message;
    }

    navigator.qt.onmessage = function(ev) {
        jsCall(ev.data);
    }
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)