How to customize user-agent for QWebView

Sometimes it is necessary to alter the user-agent header for the request sent by QWebView. Some websites may refuse your visit if you do not use a normal browser. In such case we should fake a user-agent header as if the request comes from a normal browser. If you search google for how to change the user-agent in a QWebView, you will definitely find two solutions. One is as follows:

QNetworkRequest request;
request.setUrl(QUrl(url));
request.setRawHeader("User-Agent", "your customized user-agent");
load(request);

Unfortunately, it does not work. The default user agent is emitted when you load a url in a QWebView.

The second is subclassing QWebPage to overload the protected virtual function userAgentForUrl. This function is called with the url that is being loaded so you can return different user agent for different urls. But pay special attention when you overload this function, the correct form is:

QString userAgentForUrl(const QUrl &url ) const
{
        return yournewuseragent;
}

 

Do not forget the const keyword besides the function name, otherwise you will not overload the function of QWebPage but create a new function in your subclass which will never be called.

 

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Comments are closed, but trackbacks and pingbacks are open.