首先是一個例子,網頁結構如下:
代碼如下:
index.html
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<head>
</head>
<body>
<h1>Hello World</h1>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript">
function callFunctionDemo(){
alert("Hello World");
}
</script>
</body>
</html>
js.js
;
function jsFileCall(){
alert("jsFileCall");
}
function jsFileCall2(str){
alert("str:" + str);
return str;
}
當qml是這樣的代碼:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebEngine 1.0
import QtQuick.Controls 1.4
Window {
visible: true
width: 640
height: 480
WebEngineView{
id: web
anchors.fill: parent
url: "http://127.0.0.1:9998/"
}
Button {
text: "Button"
onClicked: {
/*
var functionStr = "callFunctionDemo()";
web.runJavaScript(functionStr, function(result){
console.log(result);
});
*/
var functionStr = "jsFileCall()";
web.runJavaScript(functionStr, function(result){
console.log(String(result));
});
}
}
}
點擊按鈕後:
當是這樣的代碼:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebEngine 1.0
import QtQuick.Controls 1.4
Window {
visible: true
width: 640
height: 480
WebEngineView{
id: web
anchors.fill: parent
url: "http://127.0.0.1:9998/"
}
Button {
text: "Button"
onClicked: {
/*
var functionStr = "callFunctionDemo()";
web.runJavaScript(functionStr, function(result){
console.log(result);
});
*/
var functionStr = "jsFileCall2(12345)";
web.runJavaScript(functionStr, function(result){
console.log(String(result));
});
}
}
}
點擊按鈕後:
qml接受到的數據
下面還有種情況,當前端是vue cli的時候。這裏就簡單提一下了。
在xxx.vue中的mounted中添加window.xxxx=this;這樣在控制檯使用window.xxx.zzzz這個zzzz就是對應vue中的methods的函數,然後再qml中這樣修改即可。