【发布时间】:2019-07-09 10:43:06
【问题描述】:
我有一个包含这个的 html 页面:
<div id="ajaxloader" style="display: none;">
<div>
hello world
</div>
</div>
我可以用document.getElementById('ajaxloader').style.display读取它的显示值
我想在其显示更改为block 或none 时收到通知。
目前我正在使用计时器的愚蠢解决方案:
Timer{
running : true
repeat : true
interval: 500
onTriggered: {
var js = "document.getElementById('ajaxloader').style.display"
webView.runJavaScript(js,x=>{
if(x=="block"){
// we catch the change but its really bad solution
}
})
}
}
我正在寻找一种方法来捕捉 DOM 中的这种变化,有一种叫做 Mutation Observer 的东西,但我不知道如何在 QML 的 WebEngineView 中实现它。
我只需要一种方法来捕捉 WebEngineView 中发生的变化,或者捕捉引擎中发生的 CRUD 的事件,或者比这个计时器更好!
更新 :
例如,我们有一个访问 google.com 的网络引擎,加载完成后它将搜索文本更改为“hello world”,我们希望在不使用计时器的情况下捕捉该更改,在实际网站中,这种更改实际上发生在 CRUD 函数(ajax 请求)或其他方式:
WebChannel{
id:_channel
}
WebEngineView{
id:webEngine
height: parent.height
width: parent.width
webChannel: _channel
url : "www.google.com"
onNewViewRequested: {
request.openIn(webEngine)
}
objectName: "webView"
profile.httpCacheType: WebEngineProfile.NoCache
onLoadingChanged: {
if(loadRequest.status == WebEngineView.LoadSucceededStatus){
var js = "document.querySelector('input[role=combobox]').value = 'hello world'"
webEngine.runJavaScript(js,y=>{})
}
}
}
不要忘记在 c++ 中初始化引擎,如果没有这个,它将无法工作:QtWebEngine::initialize(); 和其他导入的东西加上你需要将它添加到 pro 文件
QT += webengine webengine-private webenginecore webenginecore-private
现在如果我使用我想把它放在一边的计时器方法,它应该是这样的:
Timer{
running : true
repeat : true
interval : 500
onTriggered:{
var js = "document.querySelector('input[role=combobox]').value"
webEngine.runJavaScript(js,y=>{console.log(y)});
// now i have to check y to see if its equals to hello world or what ever which is really bad idea to use a timer here
}
}
例如,您可以像这样观察 google 输入的变化:
var targetNode = document.querySelector('input[role=combobox]')
targetNode.oninput = function(e){this.setAttribute('value',targetNode.value)}
var config = { attributes: true, childList: true, subtree: true };
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
【问题讨论】:
-
您的 MutationObserver 仅在用户进行更改而不是在以编程方式进行更改时才有效,您是否只想在用户进行更改时检测更改?
-
@eyllanesc 有没有办法以编程方式包含更改?突变或没有任何方式都可以
标签: qt qml qtwebengine