Search code examples
c++jsonqtqwebview

Overriding page replies in QWebView


I'm attempting to intercept a page/form request within Qt's QWebView and respond in some cases with alternative content.

QNetworkReply* ngcBrowser::createRequest(Operation operation, const QNetworkRequest& request, QIODevice* ioDevice)
{
        view->page()->setNetworkAccessManager(this);

        QNetworkReply* response = NULL;

        if (request.url().path().endsWith("ajax")) 
        {
            response = QNetworkAccessManager::createRequest(operation, request, ioDevice);

            response->write("{ success: true }");
        }
        else
        {
            response = QNetworkAccessManager::createRequest(operation, request, ioDevice);
        }

        return response;
}

As you can see above I've overridden the QNAM createRequest method to receive all page requests and respond with a JSON object if the Url ends with a .ajax extension. However i'm finding it hard to write data back into the network stream.

Any hints or tips on how to go about this?

Cheers, Ben

Update:

Hi Abhijith, I've attempted your solution however it fails to connect the signal to the slot.

QNetworkAccessManager* nam = view->page()->networkAccessManager();

bool status = QObject::connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyReceived(QNetworkReply*)));

if(!status)
{
QErrorMessage errorMessage;
errorMessage.showMessage("connect failed");
errorMessage.exec();
}

Error:

Object::connect: No such slot ngcBrowser::replyRecieved(QNetworkReply*)

Update:

Ok I've managed to get his working however when i attempt to write to the IODevice is fails indicating its a ReadOnly device.

Thanks for all the help.


Solution

  • There are many ways of doing this . This is one way.

    connect(networkAccessManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyReceived(QNetworkReply*)))
    ....
    
    void replyReceived(QNetworkReply* reply)    // reply slot
    {
        if(reply->request().url().path().endsWith("ajax"))
        {
          QByteArray array = reply->readll();/*reply is cleared after this call and will not contains anything.*/
          /*Write the JSON wherever you want to in the array*/
          reply->write(array);
    
        }
    }
    

    You Have to fine tune this depending on which signal you want to listen to - replyfinished from QNAM or finished from QNetworkReply etc.