Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. LocalStorage in QWebEngineView not saved after running.
Forum Updated to NodeBB v4.3 + New Features

LocalStorage in QWebEngineView not saved after running.

Scheduled Pinned Locked Moved Unsolved Qt for Python
2 Posts 2 Posters 330 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Daic
    wrote on last edited by
    #1

    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 to localStorage. 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())
    
    
    JonBJ 1 Reply Last reply
    0
    • D Daic

      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 to localStorage. 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())
      
      
      JonBJ Online
      JonBJ Online
      JonB
      wrote on last edited by
      #2

      @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?
      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved