javascripthtmlqtwebengine

How can I fill in text (from C++) in an input text field on a web page through QWebEngine?


I would like to wrap a website in QWebEngine so I can adapt input commands using Qt's event filters and perhaps much more. The website in question requires username/email and password, and I would like to make sure I can handle the input of that text on my end, sending the strings to be filled in on the web page, and then programmatically push the login button on the same page.

I found this page, suggesting using a QWebChannel and some custom javascript to get this working. I know how to get the info of what element I want to fill in through Firefox' Web Inspector tool, but I have no clue how to

  1. pass two strings to custom JS code I'd be running through QWebChannel somehow

  2. actually write the JS code to find a specific element on a website not under my control

There are no url parameters or some such, and if I look at what the POST request looks like that is sent when I actually press "log in" in the browser, the information is encoded somehow, so replicating the actual sent data doesn't seem feasible at this point.


Solution

  • In my login page i have two variables: username, userpassword. You could use runJavaScript form QWebEnginePage to evaluate your js:

     ui->webView->page()->runJavaScript(QString("document.getElementById('username').value = '%1'").arg("example"));
     ui->webView->page()->runJavaScript(QString("document.getElementById('password').value = '%1'").arg("example"));
    

    To get the inserted text by user, you could use:

    ui->webView->page()->runJavaScript(QString("document.getElementById('username').value"),
                                              [this](const QVariant& res) {
        qDebug() << "Username = " << res.toString(); 
    });
    

    Now,just call your login button and emulate click events, post event....

    ui->webView->page()->runJavaScript(QString("document.getElementById("%1").click()).arg("example"));
    

    Im using it to login my page automatically to get the session token or cookie.