Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt QWebView class custom User-Agent

Tags:

qt

qt4

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/27073/how-to-set-user-agent-in-qwebview.html

I'm learning C++/Qt right now and I don't really understant what's explained on that website. Maybe someone knows an easy way to do it? Or can help me understand that code?

like image 500
Dan Mooray Avatar asked Oct 11 '10 14:10

Dan Mooray


2 Answers

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.

like image 180
Kaleb Pederson Avatar answered Oct 03 '22 12:10

Kaleb Pederson


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());
like image 35
goobingo Avatar answered Oct 01 '22 12:10

goobingo