Qt QWebView class custom User-Agent

前端 未结 2 2035
小蘑菇
小蘑菇 2020-12-09 21:15

Is there an easy way to setup the User-Agent the QWebView class is using?

The only relevant link I found searching was this

http://www.qtforum.org/article/2

相关标签:
2条回答
  • 2020-12-09 21:44

    simply,

    class myWebPage : public QWebPage
    {
        virtual QString userAgentForUrl(const QUrl& url) const {
            return "your user agent";
        }
    };
    
    //Attention here is new myWebPage() not new myWebPage(parent) 
    UI->webView->setPage(new myWebPage());
    
    0 讨论(0)
  • 2020-12-09 22:06

    Qt allows you to provide a user agent based on the URL rather than a single user agent no matter what the URL is. The idea then is to return the user agent any time a new webpage is created:

    class UserAgentWebPage : public QWebPage {
        QString userAgentForUrl(const QUrl &url ) const {
            return QString("My User Agent");
        }
    };
    

    In order to use that page instead of the standard page that is created, you can set that page on the browser control object before making the request:

    yourWebView->setPage(new UserAgentWebPage(parent));
    

    I would actually expect a factory to be present somewhere that will guarantee that the webpage created is always of a certain type, but I didn't see one.

    Yet another option should be to set the user agent header within the QNetworkRequest:

    QNetworkRequest request = new QNetworkRequest();
    request->setRawHeader(
        QString("User-Agent").toAscii(),
        QString("Your User Agent").toAscii()
        );
    // ... set the URL, etc.
    yourWebView->load(request);
    

    You would actually want to check whether it's toAscii() or toUtf8() or one of the other variants as I'm not sure exactly what the HTTP standard allows.

    0 讨论(0)
提交回复
热议问题