In qt4 qml the qtwebkit 1.0 the component webview has a property javaScriptWindowObjects. I used it to add javaScriptWindowObjects to the context of my webpages javascript to call c++ functions. like so
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);
}
}
}
so i can call it from the webpages javascript like so
<script type="text/javascript">
native.foo(1,2)
</script>
but in qt5 qml qtwebkit 3.0 there is no such thing like javaScriptWindowObjects
how can i achieve that in qt5 qml?
Just for the record to get this done:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With