QtWebEngine : Load URL with HTTPPost

1.6k views Asked by At

I'm porting an internal browser from QtWebKit to QtWebEngine.

I want a function to request url while posting some data. With WebKit, I could use the following:

With class WebView derived from QtWebView :

void WebView::loadPostUrl(const QUrl &url, QByteArray postdata)
{
    m_initialUrl = url;
    QNetworkRequest request = QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    load(request, QNetworkAccessManager::PostOperation, postdata);
}

Since QtWebEngine does interact with QNetworkAccessManager how can we have the same functionalities with QtWebEngine ?

Thanks

1

There are 1 answers

0
Glen van de Mosselaer On

My solution was using QWebEnginePage::runJavaScript() to script the login instead of simulating the Post Operation.

QString strLoginScript(
    "var formElts = document.getElementById('formSignIn').elements;"
    "formElts['inputLoginName'].value = '%1';"
    "formElts['inputPassword'].value = '%2';"
    "formElts['btnSignIn'].click();")
    .arg(strUsername)
    .arg(strPassword);

// execute JavaScript code on current page
webEngineView->page()->runJavaScript(strLoginScript);

The optional last parameter (not shown here) is a lambda function that executes when your JavaScript function exits and receives the last value output.

The documentation is not clear on the subject, but I think the function executes asynchronously from the main thread - otherwise you would just block execution and wait, instead of passing in an optional lambda/functor/function-pointer to execute later.