Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

screen object in JavaScript not available in a QWebEnginePage

I have a Qt application that launches Webviews using QWebChannel.

In these views, I have the JavaScript doing some stuff in order to position/resize the window depending on the screen size. The screen object is supposed to give this kind of information. (screen doc)

But in my QWebEnginePage, the screen object is empty during the whole loading process.

If I put a listener on a button to get screen.height somewhere on the page, now it works.

//js local file called in html head

//screen = {}
document.addEventListener("load", function(event) {
  //screen = {}
  new QWebChannel(qt.webChannelTransport, function(channel) {
    //screen = {}
    //stuff
    channel.object.myClass.show(function(res){ //Qt function that calls the show() method of the QWebEngineView
      //screen = {}
    });

  });

  document.getElementById("myBtn").addEventListener("click", function(){
    console.log("height:" + screen.height); // screen: 1440
  });
});

So my question is, how can I access screen values at some point in my JavaScript?

like image 464
hereismass Avatar asked Nov 09 '22 16:11

hereismass


1 Answers

I think that at the moment you are trying to access your screen object, it is not available. Indeed, your HTML file will be loaded directly, but other objects such as JavaScript objects/programs or style sheets (e.g. CSS files) will be loaded asynchronously.

It is explained in the documentation of QWebEnginePage:

The html is loaded immediately; external objects are loaded asynchronously.

Thus, while your page is not loaded, you can't access this property. However, you can access it once the page is loaded, like you are doing actually with a listener on a button. Another way to get these properties is to define Q_INVOKABLE methods in your class in order to retrieve them in the C++ side (see this answer).

like image 178
IAmInPLS Avatar answered Nov 14 '22 21:11

IAmInPLS