I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despite my understanding of what the page does, I am encountering difficulties in waiting for the JavaScript execution to complete. In order to achieve this, I am using Qt's QWebEngineView to load the page and inject JavaScript onto it as shown below:
void MainWindow::pageloaded(bool ok)
{
ui->webView->page()->runJavaScript(jQuery);
ui->webView->page()->runJavaScript(waitForKeyElement,[this](const QVariant &v) { qDebug() << v.toString();ui->webView->show();});
}
The jQuery
file being used here is jquery.min.js
, while waitForKeyElement
can be found here. Essentially, the latter function waits for specific elements to appear in the DOM before executing additional actions.
Within the same file, I have also included a function at the end:
waitForKeyElements (".x-live-elements", scrollpage);
function scrollpage (jNode) {
window.scrollTo(0, 80);
tables = document.getElementsByClassName("x-content");
table = tables[0];
table.style.backgroundColor="transparent";
document.body.style.backgroundColor = "transparent";
}
This function successfully scrolls down the page and adjusts background colors once the designated element appears on the page. However, I am facing an issue where the page content is visible to the user during these changes. My original intention was to keep the page hidden until all modifications were complete by initially calling the hide()
method for the webview.
How can I trigger the show()
function once the JavaScript operations are finished?
To address this concern, I attempted adding the following logic to the end of the waitForKeyElement.js
file:
(function (){
while(true){
var bodyStyle = window.getComputedStyle(document.body, null);
var bgcolor = bodyStyle.backgroundColor;
var transparent = 'rgba(0, 0, 0, 0)';
if (bgcolor === transparent){
break;
}
}
a = "done";
return a;
})();
In theory, this script should return once the background color of the page becomes transparent, indicating the completion of tasks. Unfortunately, the loop gets stuck indefinitely without ever meeting the exit condition.
Given that runJavascript
works asynchronously and the callback is invoked upon script completion, how can I efficiently ensure that the appropriate actions are taken only after the JavaScript execution finishes?