Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] is there a way to get element background colour ? #4282

Closed
tanneerumahesh opened this issue Oct 29, 2020 · 23 comments
Closed

[Question] is there a way to get element background colour ? #4282

tanneerumahesh opened this issue Oct 29, 2020 · 23 comments

Comments

@tanneerumahesh
Copy link

Hi guys, is there a way to get element background colour using playwright?

Tahnks

@viraxslot
Copy link

viraxslot commented Oct 29, 2020

Hey @tanneerumahesh!
Try this code:

const element = await page.waitForSelector(selector);
const color = await element.evaluate((el) => {
       return window.getComputedStyle(el).getPropertyValue('background-color');
});
console.log(color);

Be aware of this
Maybe there is a better solution, but it's my approach of doing this :)

@mxschmitt
Copy link
Member

Feature request in #11494

@isa3bel
Copy link

isa3bel commented May 26, 2022

For some reason, doing @viraxslot solution gives me a color that is an empty object. I am doing page.locator(selector).evalutate((e) => {return window.getComputedStyle(e).getPropertyValue('background-color'); });

Does his solution work for anyone else?

@viraxslot
Copy link

@isa3bel Hi, I've just made a fresh example with the locator approach:

import {test, expect} from "@playwright/test"

test("basic test", async ({page}) => {
    await page.goto("https://playwright.dev/docs/intro")
    const docsLink = page.locator("a >> text=Docs")
    const color = await docsLink.evaluate((e) => {
        return window.getComputedStyle(e).getPropertyValue("color")
    })
    expect(color).toBe("rgb(69, 186, 75)")
})

I believe it should check the color of this link:
image

Please pay attention that you have a typo in evalutate function. It should be evaluate. And please don't forget await :)
Hope it'll help you.

@isa3bel
Copy link

isa3bel commented May 27, 2022

I was wondering, why is the await keyword needed in this case? I think my program hangs if I add that keyword. Perhaps a promise is never being met? @viraxslot

@viraxslot
Copy link

@isa3bel Well, due to playwright docs evaluate function returns Promise, so you need to add await for sure: https://playwright.dev/docs/api/class-locator#locator-evaluate

And about getPropertyValue function itself, our statement will work for both cases (async or not). But as I can see this function is synchronous: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue
So, I guess evaluate won't wait and will return the value right away, because you can await synchronous functions with no problem (but it's redundant of course).

So it's hard to say what's wrong in your case. Could you please provide a reproducible example?

@shilpa32
Copy link

Hi guys, how to get element background color using playwright java?

@dourbi
Copy link

dourbi commented Nov 26, 2022

@shilpa32 did u find any method for background color in java??

@shilpa32
Copy link

shilpa32 commented Nov 30, 2022

System.out.println(page.locator("body").evaluate("element => getComputedStyle(element)['background-color']"));

@samaquartey
Copy link

this works for me in C# and should also work for Java,
you could put it in re-usable method.

await Expect(locator).ToHaveCSSAsync("background-color", "rgb color here");

@jwerre
Copy link

jwerre commented Feb 24, 2023

Has anyone run into this issue:

export const getStyle = async ( locator: Locator, property: string): Promise<string> => {
  return locator.evaluate((el) => window.getComputedStyle(el).getPropertyValue(property) );
};
getStyle(page.getByRole('button'), 'background-color');

// ERROR: locator.evaluate: ReferenceError: property is not defined

Why is it not able to read property? Since evaluate is running in a different virtual machine is this even possible?

@phungleson
Copy link

@jwerre evaluation happens in browser, so you have to manually pass the value to it, something like this

locator.evaluate((el, property) => window.getComputedStyle(el).getPropertyValue(property), property);

@yabols
Copy link

yabols commented May 24, 2023

Does anyone know how to do something similar in C#? In my case, if an element has the css display property set to block, my Playwright test needs to click an extra button. If it isn't set to block, my test should continue.

I have a similar case, and I'm also using .net version.
I tried to do something like this
var elementLocator = _elementContainer.Locator(".wfl_main_container"); var color = await elementLocator.EvaluateAsync<string>( "(element) => window.getComputedStyle(element).getPropertyValue('background-color')", elementLocator);

But it doesn't work and I get stack overflow exception :/

@samaquartey
Copy link

samaquartey commented May 24, 2023

you just have to pass the element locator and the expected color.
just copy the methods, ready to use

// Check element background-color
public async Task CheckElementBackgroundColor(ILocator locator, string color)
{
    await Expect(locator).ToHaveCSSAsync("background-color", color);
}

// Check element color
public async Task CheckElementColor(ILocator locator, string color)
{
    await Expect(locator).ToHaveCSSAsync("color", color);
}

@yabols
Copy link

yabols commented May 24, 2023

you just have to pass the element locator and the expected color. just copy the methods, ready to use

// Check element background-color
public async Task CheckElementBackgroundColor(ILocator locator, string color)
{
    await Expect(locator).ToHaveCSSAsync("background-color", color);
}

// Check element color
public async Task CheckElementColor(ILocator locator, string color)
{
    await Expect(locator).ToHaveCSSAsync("color", color);
}

So the evaluate method won't work? I don't want to assert it straight away. I need value as this is some nested object.

Maybe I'm missing something, I tried to do simple check because I thought that maybe with my page is something weird happening but with this code I have same issue, stack overflow.

`var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false
});

    var page = await browser.NewPageAsync();
    await page.GotoAsync("http://google.com");
    var ele = page.GetByRole(AriaRole.Button, new() { Name = "Google Search" });
    var backgroundColor =  await page.EvaluateAsync<string>(
       @"(element) => {
                const style = window.getComputedStyle(element);
                return style.getPropertyValue('background-color');
            }", ele);

    var backgroundColor2 = await page.EvaluateAsync<string>(
        "(element) => getComputedStyle(element).getPropertyValue('background-color')", ele);`

@InTouch1988
Copy link

Has anyone run into this issue:

export const getStyle = async ( locator: Locator, property: string): Promise<string> => {
  return locator.evaluate((el) => window.getComputedStyle(el).getPropertyValue(property) );
};
getStyle(page.getByRole('button'), 'background-color');

// ERROR: locator.evaluate: ReferenceError: property is not defined

Why is it not able to read property? Since evaluate is running in a different virtual machine is this even possible?

Did you find any solution? I faced with the same issue. The solution, provided by phungleson doesn't work, still see the error

@jwerre
Copy link

jwerre commented May 25, 2023

@InTouch1988, @phungleson solution does work. Here's what I have (Typescript)

/**
 * Retrieve a computed style for an element.
 *
 * @function getStyle
 * @async
 * @param locator {Locator} The Playwright locator to evaluate (see: https://playwright.dev/docs/locators)
 * @param property {string} The CSS property for the style to retrieve
 * @returns Promise<string> The style value
 */
export const getStyle = async (locator: Locator, property: string): Promise<string> => {
   return locator.evaluate( (el, property) => window.getComputedStyle(el)
     .getPropertyValue(property), property );
};


test('get button background color', async ({ page }) => {
  cost btnBgColor = await getStyle(page.getByRole('button'), 'background-color');
  expect(btnBgColor).toBe('rgb(255, 0, 0)')
});

@GStasiakVolue
Copy link

Working solution in C#:

private ILocator _btn => _page.Locator("button");
var backgroundColor = await _btn.EvaluateAsync<string>(@"element => window.getComputedStyle(element).getPropertyValue('background-color')");

@samaquartey
Copy link

Great thanks @GStasiakVolue
I just made it resuable: works perfectly

public string GetElementBackgroundColor(ILocator locator)
{
var backgroundColor = locator.EvaluateAsync(@"element => window.getComputedStyle(element).getPropertyValue('background-color')").Result;
return backgroundColor.ToString();
}

@lihka1202
Copy link

I'm not too sure but as of 29th January 2024 you can make use of the toHaveCSS assertion to verify the colour. In my case I wanted to find the background colour of the page (should work for any element), and I did something along the following lines:

await expect(this.page.locator('body')).toHaveCSS('background-color', 'rgb(250, 250, 250)')

@matusdrobuliak66
Copy link

matusdrobuliak66 commented May 15, 2024

In Playwright for Python:

_button = page.get_by_role(...)
_button_style = button.evaluate("el => window.getComputedStyle(el)")
print(_button_style['backgroundColor'])  # returns 'rgb(105, 105, 255)'

@dongthg7
Copy link

dongthg7 commented Jan 15, 2025

You can try this:
const backgroundColor = await element.evaluate((e) => { return e.style.backgroundColor; });
It works for me !

@LinhDo-LGG
Copy link

You can try this: const color = await element.evaluate((e) => { return e.style.color; }); It works for me !

Thank you! you save my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests