【Qt for the first time in the rivers and lakes】Cookie management, JavaScript interaction, page printing, history management and other functional examples

Yuxian: CSDN content partner, CSDN new star mentor, 51CTO (Top celebrity + expert blogger), github open source enthusiast (secondary development of go-zero source code, game back-end architecture https://github.com/Peakchen)

    

 

Qt WebEngine is a browser engine based on the Chromium engine, which provides many functions to manage Web pages, such as Cookie management, JavaScript interaction, page printing, history management, etc.

a preliminary realization

The following describes how to implement these functions:

1. Cookie management

Qt WebEngine provides the QWebEngineCookieStore class to manage cookies for Web pages. We can use the QWebEngineProfile::defaultProfile() function to get the default QWebEngineProfile object, and use the QWebEngineProfile::setPersistentCookiesPolicy() function to set the persistence of the cookie. Then, we can use the QWebEngineProfile::cookieStore() function to get the QWebEngineCookieStore object and use it to manage cookies. For example, the following code demonstrates how to set cookie persistence and add cookies to a web page:

QWebEngineProfile* profile = QWebEngineProfile::defaultProfile();
profile->setPersistentCookiesPolicy(QWebEngineProfile::AllowPersistentCookies);

QWebEngineCookieStore* cookieStore = profile->cookieStore();
QNetworkCookie cookie("name", "value");
cookie.setDomain("example.com");
cookie.setPath("/");
cookieStore->setCookie(cookie, QUrl("http://example.com"));

In the above code, we first use the QWebEngineProfile::defaultProfile() function to get the default QWebEngineProfile object, and use the QWebEngineProfile::setPersistentCookiesPolicy() function to set the persistence of the cookie. Then, we use the QWebEngineProfile::cookieStore() function to get the QWebEngineCookieStore object, and use the setCookie() function to add cookies to the Web page.

2. JavaScript interaction

Qt WebEngine provides the QWebEnginePage::runJavaScript() function to interact with the JavaScript code of the Web page. We can use this function to execute JavaScript code and get the return value of JavaScript code in C++ code. For example, the following code demonstrates how to execute JavaScript code and get the return value of JavaScript code in C++ code:

QWebEngineView view;
view.show();

QWebEnginePage* page = view.page();
QVariant result = page->runJavaScript("document.title");
qDebug() << "Page title:" << result.toString();

In the above code, we first create a QWebEngineView object and display it using the show() function. Then, we use the QWebEngineView::page() function to get the QWebEnginePage object, and use the QWebEnginePage::runJavaScript() function to execute the JavaScript code. Finally, we use the toString() function to convert the return value to a string and output it to the console.

3. Page printing

Qt WebEngine provides the QWebEnginePage::print() function to print Web pages. We can use this function to print a web page to a printer or to a PDF file. For example, the following code demonstrates how to print a web page to a PDF file:

QWebEngineView view;
view.show();

QWebEnginePage* page = view.page();
page->printToPdf("page.pdf", [](const QByteArray& pdf){
    QFile file("page.pdf");
    if(file.open(QIODevice::WriteOnly))
    {
        file.write(pdf);
        file.close();
    }
});

In the above code, we first create a QWebEngineView object and display it using the show() function. Then, we use the QWebEngineView::page() function to get the QWebEnginePage object, and use the QWebEnginePage::printToPdf() function to print the Web page to a PDF file. Finally, we use lambda expressions to process the generated PDF files.

4. History management

Qt WebEngine provides the QWebEngineHistory class to manage Web browsing history. We can use the QWebEnginePage::history() function to get the QWebEngineHistory object and use it to manage the Web browsing history. For example, the following code demonstrates how to go back and forward in web browsing history:

QWebEngineView view;
view.show();

QWebEnginePage* page = view.page();
QWebEngineHistory* history = page->history();
history->back();
history->forward();

In the above code, we first create a QWebEngineView object and display it using the show() function. Then, we use the QWebEngineView::page() function to get the QWebEnginePage object, and use the QWebEnginePage::history() function to get the QWebEngineHistory object. Finally, we use the back() function and forward() function to go back and forward in the web browsing history.

Two supplementary implementations

Supplement: The above-mentioned cookie management, JavaScript interaction, page printing, history management and other functions can all be implemented in Qt WebEngine through the signal and slot mechanism. The following are detailed descriptions and code examples:

In addition to using the QWebEngineCookieStore class for cookie management, Qt WebEngine also provides the QWebEngineProfile::downloadRequested() signal and the QWebEngineProfile::profileCreated() signal, which can be used to intercept and modify cookies.

For example, the following code demonstrates how to intercept cookies using the QWebEngineProfile::downloadRequested() signal:

QWebEngineProfile* profile = QWebEngineProfile::defaultProfile();
QObject::connect(profile, &QWebEngineProfile::downloadRequested,
                 [=](const QWebEngineDownloadItem& download){
    const QList<QNetworkCookie>& cookies = download.cookies();
    // 处理Cookie
});

In the above code, we use the QWebEngineProfile::defaultProfile() function to get the default QWebEngineProfile object, and use the QObject::connect() function to connect the QWebEngineProfile::downloadRequested() signal. When the web page requests to download, this signal is triggered, and a QWebEngineDownloadItem object is passed as a parameter, which contains the information of the download request, including Cookie.

In addition to using the QWebEnginePage::runJavaScript() function for JavaScript interaction, Qt WebEngine also provides the QWebEnginePage::javaScriptConsoleMessage() signal and the QWebEnginePage::javaScriptPrompt() signal, which can be used to process the output and input of JavaScript code in C++ code.

For example, the following code demonstrates how to use the QWebEnginePage::javaScriptConsoleMessage() signal to output the output of JavaScript code:

QWebEngineView view;
view.show();

QWebEnginePage* page = view.page();
QObject::connect(page, &QWebEnginePage::javaScriptConsoleMessage,
                 [=](const QString& message, int lineNumber, const QString& sourceID){
    qDebug() << "JavaScript output:" << message << "at line" << lineNumber << "in" << sourceID;
});

page->runJavaScript("console.log('Hello from JavaScript!')");

In the above code, we use the QWebEngineView class to create a Web page, and use the QWebEngineView::page() function to get the QWebEnginePage object. Then, we use the QObject::connect() function to connect to the QWebEnginePage::javaScriptConsoleMessage() signal, which is triggered when JavaScript code is output to the console, passing the output message, line number, and source ID as parameters. Finally, we execute JavaScript code using the QWebEnginePage::runJavaScript() function, which outputs a message to the console.

In addition to using the QWebEnginePage::print() function for page printing, Qt WebEngine also provides the QWebEnginePage::printRequested() signal and the QWebEnginePage::pdfPrintingFinished() signal, which can be used to process the output and results of page printing in C++ code.

For example, the following code demonstrates how to print a Web page to a PDF file using the QWebEnginePage::printRequested() signal and the QWebEnginePage::pdfPrintingFinished() signal:

QWebEngineView view;
view.show();

QWebEnginePage* page = view.page();
QObject::connect(page, &QWebEnginePage::printRequested, [=](QWebEnginePdfPrinter* printer){
    printer->setOutputFileName("page.pdf");
    printer->printToPdf();
});
QObject::connect(page, &QWebEnginePage::pdfPrintingFinished, [=](const QByteArray& pdf){
    QFile file("page.pdf");
    if(file.open(QIODevice::WriteOnly))
    {
        file.write(pdf);
        file.close();
    }
});

view.load(QUrl("http://www.example.com"));

In the above code, we use the QWebEngineView class to create a Web page, and use the QWebEngineView::page() function to get the QWebEnginePage object. Then, we use the QObject::connect() function to connect to the QWebEnginePage::printRequested() signal, which is triggered when the web page requests printing, and pass a QWebEnginePdfPrinter object as a parameter. We can use this object to set the output filename and perform printing operations. Finally, we use the QObject::connect() function to connect to the QWebEnginePage::pdfPrintingFinished() signal, which is triggered when printing is complete, passing the binary data of the resulting PDF file as an argument. In the processing function of this signal, we save the generated PDF file locally.

In addition to using the QWebEngineHistory class for history management, Qt WebEngine also provides the QWebEnginePage::urlChanged() signal and the QWebEnginePage::titleChanged() signal, which can be used to process changes in Web browsing history in C++ code.

For example, the following code demonstrates how to use the QWebEnginePage::urlChanged() and QWebEnginePage::titleChanged() signals to monitor changes in the web browsing history:

QWebEngineView view;
view.show();

QWebEnginePage* page = view.page();
QObject::connect(page, &QWebEnginePage::urlChanged, [=](const QUrl& url){
    qDebug() << "Page URL changed:" << url;
});
QObject::connect(page, &QWebEnginePage::titleChanged, [=](const QString& title){
    qDebug() << "Page title changed:" << title;
});

view.load(QUrl("http://www.example.com"));

In the above code, we use the QWebEngineView class to create a Web page, and use the QWebEngineView::page() function to get the QWebEnginePage object. Then, we use the QObject::connect() function to connect the QWebEnginePage::urlChanged() signal and the QWebEnginePage::titleChanged() signal, which are triggered when the URL or title of the web browsing history changes. We output the changed URL or title in the handler function of these signals. Finally, we use the QWebEngineView::load() function to load the web page, which triggers the QWebEnginePage::urlChanged() and QWebEnginePage::titleChanged() signals.

Qt WebEngine provides a wealth of functions to manage Web pages, including Cookie management, JavaScript interaction, page printing, history management, etc. Developers can choose appropriate methods and APIs to implement these functions according to their own needs. At the same time, through the signal and slot mechanism, developers can also handle events and changes of Web pages in C++ code.

Guess you like

Origin blog.csdn.net/feng1790291543/article/details/131805351
Recommended