如何在 python 和 QtWebEngine 中启用 allowGeolocationOnInsecureOrigins

Posted

技术标签:

【中文标题】如何在 python 和 QtWebEngine 中启用 allowGeolocationOnInsecureOrigins【英文标题】:How to enable allowGeolocationOnInsecureOrigins in python and QtWebEngine 【发布时间】:2019-02-28 12:07:39 【问题描述】:

我正在使用 Python 和 PyQt5 制作网络浏览器,我想在我的网络浏览器中启用 allowGeolocationOnInsecureOrigins,以便我可以通过 Google Geo Location API 访问用户位置。

代码

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

错误

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

【问题讨论】:

【参考方案1】:

枚举 QWebEngineSettings::WebAttribute

QWebEngineSettings::AllowWindowActivationFromjavascript 自 Qt 5.7 起,只有 HTTPS 等安全来源能够请求 地理位置功能。 这提供了一个覆盖以允许非安全源再次访问 Geolocation。 默认禁用。 (在 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_())

【讨论】:

我面临这个错误 self.browser.page().settings().setAttribute(QWebEngineSettings.AllowGeolocationOnInsecureOrigins, True) AttributeError: type object 'QWebEngineSettings' has no attribute 'AllowGeolocationOnInsecureOrigins' 在您运行的问题中发布一个示例。 非常感谢您的回复。您需要检查代码吗? 对不起,我不需要任何东西。我发布了一个示例来帮助您。你写道,我的例子给你一个错误。所以我建议发布一个给出错误的示例。

以上是关于如何在 python 和 QtWebEngine 中启用 allowGeolocationOnInsecureOrigins的主要内容,如果未能解决你的问题,请参考以下文章

QtWebEngine 和 WebView 有啥区别? [复制]

Qt5.4-QtWebEngine中如何获取网页的contentSize

使用 QtWebEngine 编译 PyQt5 应用程序

单击链接时如何修改 QtWebEngine 行为?

如何从源代码构建 QtWebEngine 5.10

如何在 QtWebEngine QML 应用程序中设置用户代理