简体   繁体   中英

How to allow notifications on headless chrome using selenium webdriver

I am trying to run UI automation tests with seleinum chromedriver. 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?

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.

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". Executing the following code will show "granted", but Notification.permission will return "denied" due to the bug.

Notification.requestPermission().then(r => console.log(r))

You can track the status of this issue here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM