Display the QWebEngineView page only after the completion of a JavaScript script

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?

Answer №1

I managed to come up with a solution that worked for me:

Initially, before executing jquery and waitForKeyElement, I decided to hide the entire body.

ui->webView->page()->runJavaScript("$('body').hide();");
ui->webView->page()->runJavaScript(jQuery);
ui->webView->page()->runJavaScript(waitForKeyElement);

Then in the waitForKeyElement.js file, I modified my scrollpage function to look like this:

function scrollpage (jNode) {
  tables = document.getElementsByClassName("x-content");
  table = tables[0];
  table.style.backgroundColor="transparent";
  document.body.style.backgroundColor = "transparent";
  $('body').show();
  window.scrollTo(0, 80);
}

Although not perfect, this approach served its purpose adequately for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attributes for 'v-bind' directives must have a value specified

Struggling to implement a tree structure in vue.js and encountering an issue with element props. Any assistance would be greatly appreciated. I've attempted using :content="{{tempCont}}" as well as content="{{tempCont}}", but neither approach proved ...

NodeJS has a knack for replying even before the function has completed

Struggling with a NodeJS and Express API for a school project. The getAuthUserId function is not working as expected. It decodes the JWT token to retrieve the user Id from the mongoDB server. However, when calling this function in a REST call "/user/authT ...

Having trouble transmitting JSON data to an Express server through the browser

I have set up two servers: the first one is for frontend (localhost:7200), and the second one is for backend (localhost:7300). There is a test request made by the frontend to the backend on the route '/test'. The issue arises when I attempt to s ...

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

Retrieving over 300,000 rows from elasticsearch and saving them as a .csv document

Hi there, I am currently working on a website in nodejs that utilizes an Elasticsearch database. One of my indexes, 'bigData*', contains 366,844 rows with each row consisting of 25 items, each being a different string of varying sizes (with a max ...

Generate a PDF document on the user's device

Is there a way for me to trigger the print command on a PDF file without relying on Adobe PDF viewer's print button? I'm interested in using a separate event instead of the print button within the PDF viewer. Is this achievable? ...

I am attempting to pass information through the body of an Axios GET request to be used in a Django backend, but when I try to print the request.body

As reported by Axios, it seems that this is a feasible solution: https://github.com/axios/axios/issues/462#issuecomment-252075124 I have the code snippet below where pos_title contains a value. export function getQuery(pos_code, id) { if (id === 94) ...

Issue with AngularJS binding not updating when the initial value is null and then changed

I am encountering an issue with my binding not updating, and I have a hypothesis on why it's occurring, but I'm unsure about how to resolve it. Within my controller, there is a company object that includes a property called user, which may or ma ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...

"Exploring the world of JavaScript through the lens of time

This summer, I have the opportunity to assist a friend with some JavaScript challenges on his website. The main issue seems to revolve around technical difficulties with online form submissions. Unfortunately, there are instances where we struggle to verif ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

What solutions are available for resolving the devServer issue in webpack?

Any help or advice would be greatly appreciated. I have configured webpack and everything works in production mode, but the webpack-dev-server is not recognizing static files and is giving the error "Cannot get /". How can I resolve this issue? Thank you i ...

Maintain dropdown menu visibility while navigating

I'm having an issue with my dropdown menu. It keeps sliding up when I try to navigate under the sub menu. I've spent all day trying to fix it, testing out various examples from the internet but so far, no luck. Any help would be greatly apprecia ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

Exploring arrays and objects in handlebars: A closer look at iteration

Database Schema Setup var ItemSchema = mongoose.Schema({ username: { type: String, index: true }, path: { type: String }, originalname: { type: String } }); var Item = module.exports = mongoose.model('Item',ItemSchema, 'itemi ...

Eliminate any unnecessary zeros at the end of a number within AngularJS interpolation

Although there are solutions available for plain JavaScript code, unfortunately they are not applicable in this particular scenario. I have a table that needs to be populated with data. The current code snippet is as follows: <tr ng-repeat="rows in $ ...

Dividing a JSON string and incorporating them into individual tds using AngularJS

Currently, I am working on extracting values from a JSON string by splitting it at the ":" and displaying the two values in separate td tags. function testCtrl($scope) { $scope.response = {"name":["The name field is required."],"param":["Hobby: Coding", " ...

What is the reason behind the code breaking when a newline is added between `return` and `(`?

After investigating my query, it seems that a peculiar issue arises in the code where setState fires and render method gets hit, but nothing rerenders The code functions correctly when there is no newline between the return statement and opening parenthes ...

What is the method for deactivating a form input field in Angular Formly?

Is there a specific way to disable a form input field using Angular Formly? I have tried searching online and cannot find a clear answer. Even after checking Formly's 'field configuration docs', I only found one mention of the word 'dis ...