Search code examples
qmlqwebview

How to set cookie with QWebview in QML?


I am using QWebView in QML. I want to show web site that needs authentication. Data should be passed via standard cookie. Any help? Additional link or example would be great.

Thank in advance.


Solution

  • By default, the default QNetworkAccessManager used by webkit have its own (non-persistent) cookie jar, aka QNetworkCookieJar.

    This will handle the sending and receiving of cookies during the life span of a QWebPage.

    To keep the same cookie jar across multiple pages, you have to:

    1. Create an instance of a QNetworkCookieJar, possibly subclassing it to make it persistent
    2. attach this cookie jar to each newly created QWebPage

    Example of a persistent cookie jar saved to settings:

    class PersistentCookieJar : public QNetworkCookieJar {
    public:
        PersistentCookieJar(QObject *parent) : QNetworkCookieJar(parent) { load(); }
        ~PersistentCookieJar() { save(); }
    
    public:
        void save()
        {
            QList<QNetworkCookie> list = allCookies();
            QByteArray data;
            foreach (QNetworkCookie cookie, list) {
                if (!cookie.isSessionCookie()) {
                    data.append(cookie.toRawForm());
                    data.append("\n");
                }
            }
            QSettings settings;
            settings.setValue("Cookies",data);
        }
    
        void load()
        {
            QSettings settings;
            QByteArray data = settings.value("Cookies").toByteArray();
            setAllCookies(QNetworkCookie::parseCookies(data));
        }
    };
    

    To use:

    QWebView* vw = new QWebView(this);
    PersistenCookieJar* jar = new PersistenCookieJar(this);
    vw->page()->networkAccessManager()->setCookieJar(jar);  // the jar is reparented to the page
    jar->setParent(this);  // reparent to main widget to avoid destruction together with the page