[SOLVED] WebView with persistent session

Hi all,

I’m trying to preserve session data for a webview to keep cookies and website connections. Based on my understanding from reading the documentation, persistence is achieved by WebKit.NetworkSession which itself creates storage related objects for cookies and caches.

I have come up with the following minimal example but it does not work. Every time I re-open the app, I end up disconnected. Any help would be welcome.

import sys
import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("WebKit", "6.0")
from gi.repository import Gtk, Adw, WebKit


class MainWindow(Gtk.ApplicationWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.set_default_size(480, 512)

        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.set_child(self.box)

        network_session = WebKit.NetworkSession(
            data_directory="/tmp/data", cache_directory="/tmp/cache"
        )
        self.webview = WebKit.WebView(network_session=network_session)
        self.webview.load_uri("https://www.linuxfr.org")
        self.webview.set_vexpand(True)
        self.box.append(self.webview)

        self.connect("destroy", lambda *args: self.webview.try_close())


class MyApp(Adw.Application):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.connect("activate", self.on_activate)

    def on_activate(self, app):
        self.win = MainWindow(application=app)
        self.win.present()


app = MyApp(application_id="com.example.GtkApplication")
app.run(sys.argv)

Solved by saving all cookies. The doc for CookieManager.set_persistent_storage says it is concerned with non-session cookies, but calling it anyway fixes the problem. I suppose many websites out there must be using non-session cookies for authentication.

So one just needs to add the following to the example above:

self.webview.get_network_session().get_cookie_manager().set_persistent_storage(
            "/tmp/cookies.sqlite", WebKit.CookiePersistentStorage.SQLITE
        )

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.