Qt工作笔记-WebEngineView调用web站点中的JS脚本(含Vue Cli脚本)

首先是一个例子,网页结构如下:

代码如下:

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中这样修改即可。

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/106917130