[英]How to allow notifications on headless chrome using selenium webdriver
I am trying to run UI automation tests with seleinum chromedriver.我正在尝试使用 seleinum chromedriver 运行 UI 自动化测试。 My tests work until I switch to headless, where it seems to default to an incognito browser and will not allow notifications.
我的测试一直有效,直到我切换到无头,它似乎默认为隐身浏览器并且不允许通知。 Allowing browser notifications is required for the application I am testing.
我正在测试的应用程序需要允许浏览器通知。 Is there a way to prevent chromedriver from defaulting to incognito?
有没有办法防止 chromedriver 默认为隐身模式?
Here is how I set up my driver:这是我设置驱动程序的方法:
chrome_options = Options()
if maximized:
chrome_options.add_argument("start-maximized")
if headless:
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920x1080")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--use-fake-ui-for-media-stream")
chrome_options.add_argument("--disable-web-security")
chrome_options.add_experimental_option("prefs", {
"profile.default_content_setting_values.notifications": 1
})
# Initialize webdriver with given options and executable path of Chrome Driver
driver_path = "/PATH/to/driver"
driver = webdriver.Chrome(executable_path=driver_path, chrome_options=chrome_options)
It's not possible at this time: Prefs don't work in headless mode (probably by design).目前不可能:首选项在无头模式下不起作用(可能是设计使然)。
There's a workaround however, but it doesn't work at the moment, because of the bug in Chromium.但是有一个解决方法,但由于 Chromium 中的错误,它目前不起作用。
Workaround code:解决方法代码:
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Browser.grantPermissions', 'params': { 'permissions': [ 'notifications' ], 'origin': 'https://example.com'}}
command_result = driver.execute("send_command", params)
This code executes DevTools command that grants notification permission to domain "example.com".此代码执行将通知权限授予域“example.com”的 DevTools 命令。 Executing the following code will show "granted", but
Notification.permission
will return "denied" due to the bug.执行以下代码将显示“granted”,但
Notification.permission
由于该错误将返回“denied”。
Notification.requestPermission().then(r => console.log(r))
You can track the status of this issue here .您可以在 此处跟踪此问题的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.