Search code examples
pythonpyqt5qtwebengine

How to enable incognito mode in PyQtWebEngine?


I am making a web browser using PyQtWebEngine but how will I give the feature of incognito mode in it.


Solution

  • The answer is in the example that I already pointed out in a previous post: WebEngine Widgets Simple Browser Example. In the Implementing Private Browsing section they point out that it is enough to provide a QWebEngineProfile() different from QWebEngineProfile::defaultProfile() since the latter is shared by all pages by default, which is what is not searched for in a private browsing.

    from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
    
    
    class WebView(QtWebEngineWidgets.QWebEngineView):
        def __init__(self, off_the_record=False, parent=None):
            super().__init__(parent)
            profile = (
                QtWebEngineWidgets.QWebEngineProfile()
                if off_the_record
                else QtWebEngineWidgets.QWebEngineProfile.defaultProfile()
            )
            page = QtWebEngineWidgets.QWebEnginePage(profile)
            self.setPage(page)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        view = WebView(off_the_record=True)
    
        view.load(QtCore.QUrl("https://www.qt.io"))
        view.show()
    
        sys.exit(app.exec_())