1

I have a simple Qt application that loads a page in a QWebEngineView. I would like to redirect all http requests with the word "static" in the url to local files. Using WebUrlRequestInterceptor I reimplemented the interceptRequest method. Here is the code:

class MyWebUrlRequestInterceptor : public QWebEngineUrlRequestInterceptor
{
public:
    void interceptRequest(QWebEngineUrlRequestInfo &info) {
        if (info.requestUrl().toString().contains("static")) {
            QString newUrl = QDir::currentPath() + info.requestUrl().toString().mid(21, info.requestUrl().toString().length());
            qDebug() << "new url = " << newUrl;
            info.redirect(QUrl::fromLocalFile(newUrl));
        }
    }
};

In main function I did

MyWebUrlRequestInterceptor *wuri = new MyWebUrlRequestInterceptor();
QWebEngineProfile::defaultProfile()->setRequestInterceptor(wuri);

And the interceptRequest seems to work fine, but I get a message.

Not allowed to load local resource

I searched online and I many people are saying that I should add the --disable-web-security flag. So i did in my .pro file:

QMAKE_CXXFLAGS += --disable-web-security

But it doesn't seem to be working. Am I doing something wrong? Is there a different solutions? Could I make custom protocols to serve local files and redirect to them in Qt as a workaround?

I'm using Qt 5.9.1 and QtCreator 4.3.1.

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
madasionka
  • 812
  • 2
  • 10
  • 29

1 Answers1

1

I would block the request using QWebEngineUrlRequestInfo::block and load the local file in the QWebEngineView (even read the local file on the fly and pass its content to the view through QWebEngineView::setHtml).

Or listen locally for incoming http requests, using local dir as web root, and eventually redirect to localhost when needed, which implies using an external web server or building a minimal one, maybe integrated in your app. If you go for integrating it, I would consider this one: https://github.com/cesanta/mongoose.

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • Thanks @p-a-o-l-o! I'm not sure I understand. If the page is asking for an image, how can I load it via `setHtml`? – madasionka Nov 15 '17 at 08:44
  • If the file content is not html, you'd be better using a local web server, as suggested. Before trying to embed one, you can test this solution using an external one, maybe express, if you're into nodejs (https://expressjs.com) – p-a-o-l-o Nov 15 '17 at 11:09