LocalStorage in QWebEngineView not saved after running.
Unsolved
Qt for Python
-
Hello everyone,
I’m currently working on a PySide6 application that uses
QWebEngineView
to display a simple HTML page. The simple example page uses JavaScript to store the "last open time" in localStorage. However, no matter how I set it up, the value for the last_open_time always shows as null each time I run the application, even though I’m saving it tolocalStorage
. But when I run the html file in browser, it can work correctly.import sys from pathlib import Path from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget from PySide6.QtWebEngineWidgets import QWebEngineView from PySide6.QtWebEngineCore import QWebEngineProfile, QWebEnginePage CACHE_PATH = Path(__file__).parent / "cache" CACHE_PATH.mkdir(exist_ok=True) class MyWebEngineView(QWebEngineView): def __init__(self, profile, parent=None): super().__init__(parent) # Use the passed profile for this WebEngineView to ensure persistent localStorage self.setPage(QWebEnginePage(profile, self)) # Load the HTML content self.setHtml(self.create_html()) def create_html(self): """Create simple HTML content with JavaScript to manage localStorage.""" html_content = """ <!DOCTYPE html> <html> <head><title>Web Page</title></head> <body> <h1>Welcome to the Web Page</h1> <p>Last open time: <span id="last_open_time">null</span></p> <script> // Get the last open time from localStorage var lastOpenTime = localStorage.getItem('last_open_time'); // If lastOpenTime exists, display it; otherwise, show null if (lastOpenTime) { document.getElementById('last_open_time').textContent = lastOpenTime; } else { document.getElementById('last_open_time').textContent = 'null'; } // Save the current open time to localStorage var currentTime = new Date().toISOString(); localStorage.setItem('last_open_time', currentTime); </script> </body> </html> """ return html_content class MainWindow(QMainWindow): def __init__(self): super().__init__() # Create a shared QWebEngineProfile with persistent storage profile = QWebEngineProfile.defaultProfile() # # Tried these, also didn't work # profile.setCachePath(CACHE_PATH.as_posix()) # profile.setPersistentStoragePath(CACHE_PATH.as_posix()) # profile.setHttpCacheType(QWebEngineProfile.HttpCacheType.DiskHttpCache) # Create QWebEngineView instance using the shared profile view = MyWebEngineView(profile) # Set up layout and main window layout = QVBoxLayout() layout.addWidget(view) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) self.setWindowTitle("Last Open Time Example") if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
-
@Daic
I don't know, but start by verifying- Setting attribute QWebEngineSettings::LocalStorageEnabled is true.
- QWebEngineProfile::persistentStoragePath() is set to where you expect, does it get updated?