本文介绍了从 webviews Javascript 调用 C++ 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 qt4 qml qtwebkit 1.0 中,组件 webview 有一个属性 javaScriptWindowObjects
.我用它来将 javaScriptWindowObjects 添加到我的网页 javascript 的上下文中以调用 c++ 函数.像这样
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);
}
}
}
所以我可以像这样从网页javascript调用它
so i can call it from the webpages javascript like so
<script type="text/javascript">
native.foo(1,2)
</script>
但是在 qt5 qml qtwebkit 3.0 中没有像 javaScriptWindowObjects
but in qt5 qml qtwebkit 3.0 there is no such thing like javaScriptWindowObjects
我如何在 qt5 qml 中实现?
how can i achieve that in qt5 qml?
推荐答案
仅作记录:
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>
这篇关于从 webviews Javascript 调用 C++ 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!