QML中 Webview 元素的runJavaScript() 函数的使用方法

QML 中的 WebViewrunJavaScript() 函数

该函数能够通过函数名调用 HTML 文件中 位于标签 <script> </script> 之间的 JS 函数,能够附带参数 比如:

HTML 文件中 script 代码如下:


Qt 调用代码如下:
    WebView {
        id: webView
        width: parent.width
        height: parent.height - mapToptool.height - 1
        anchors.top: mapToptool.bottom
        anchors.topMargin: 1
        url: mapService.backUrl()
        onLoadProgressChanged: {
            if(webView.loadProgress == 100){
                 mapService.getAllPoiData();
            }
        }
    }
    Connections {
        target: mapService
        onBackmessage: {
            if(mapService.getBackMessage().length > 0){
                //console.log(mapService.getBackMessage());
                var json = JSON.parse(mapService.getBackMessage());
                var data = [];
                for(var i=0;i<json["size"];i++){
                    var lo = json["contents"][i]["location"][0];
                    var la = json["contents"][i]["location"][1];
                    data.push(lo);
                    data.push(la);
                }
                var queryStr = "createPoi("+JSON.stringify(data)+");";
                webView.runJavaScript(queryStr, function(result) { console.log(result); });
            }
        }
    }

 



该功能可以实现通过上传本地数据,执行 JS 函数,得到需要的网页。然后展示出来!

特别注意: 当 WebView 没有加载完成前 执行了 runJavaScript() 函数时,无法生效,用上图的方式调用,亲测可行!然后,该 API 只能支持 Android 4.3 及以上版本,低版本无效,本人在 Android 5.0 上测试的,其他没测试过!

 

posted @ 2017-04-12 10:42  Mtr1994  阅读(3998)  评论(0编辑  收藏  举报