'How to detect if Chrome browser is headless in selenium?

I'm writing a selenium test which has different behavior given whether the chrome browser was started as headless or not. My question is in my test how do I detect if the browser is headless for my conditional flow?



Solution 1:[1]

https://antoinevastel.com/bot%20detection/2018/01/17/detect-chrome-headless-v2.html#:~:text=In%20order%20to%20automate%20Chrome,possible%20to%20detect%20Chrome%20headless.

driver.execute_script("return navigator.plugins.length == 0")

Solution 2:[2]

I just find this way for that.

Options its a list, so you have to find the "--headless" element in there.

opc = Options()
opc.add_argument('headless')

in this case, the position of the element in the list is [0], so you only have to to something like this:

if (opc.arguments[0]=="--headless"):
    print("Do something")

Solution 3:[3]

You need to explicitly add the argument "--headless" to your chromeOptions object when starting an instance of chrome headlessly. If you're writing, for example, a test framework for a website you probably have some sort of browser creator class that is able to give you different browsers to work with. Why not save that argument as an additional member of that class?

Another simpler option if you don't have a that sort of factory design in your code is just

options = webdriver.ChromeOptions
options.add_argument("--headless")
print(options.arguments)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user123456789
Solution 2 Carlost
Solution 3 Trevor K