Search code examples
python-3.xpyqt5qwebengineview

How to enable allowGeolocationOnInsecureOrigins in python and QtWebEngine


I'm making a web browser in Python and PyQt5 and I want to enable allowGeolocationOnInsecureOrigins in my web browser so I can access users location via Google Geo Location API.

Code

self.browser = QWebEngineView()
self.browser.allowGeolocationOnInsecureOrigins(1) 

Error

self.browser.allowGeolocationOnInsecureOrigins(1)
AttributeError: 'QWebEngineView' object has no attribute 'allowGeolocationOnInsecureOrigins'

Solution

  • enum QWebEngineSettings::WebAttribute

    QWebEngineSettings::AllowWindowActivationFromJavaScript Since Qt 5.7, only secure origins such as HTTPS have been able to request Geolocation features. This provides an override to allow non secure origins to access Geolocation again. Disabled by default. (Added in Qt 5.9)

    import sys
    from PyQt5.QtCore    import QUrl
    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings
    
    app = QApplication(sys.argv)
    
    browser = QWebEngineView()
    browser.page().settings().setAttribute(                            # <---
        QWebEngineSettings.AllowGeolocationOnInsecureOrigins, True)    # <---
    
    browser.load(QUrl("https://doc.qt.io/qt-5/qwebenginesettings.html#WebAttribute-enum"))
    browser.show()
    
    sys.exit(app.exec_())
    

    enter image description here