How to verify a button's disabled state in Puppeteer?

I’m trying to use Puppeteer to check if a button is disabled. Here’s what I’m dealing with:

My button starts off disabled:

<button type="submit" class="my-button primary-btn large-btn" disabled>

When conditions are met, it becomes enabled:

<button type="submit" class="my-button primary-btn large-btn">

The tricky part is that the disabled attribute doesn’t have a value. I can’t figure out how to check for it.

If it had a value like disabled="true", I could do something like:

const button = await page.$('button');
const isDisabled = await button.evaluate(el => el.disabled);
console.log(isDisabled);

But that doesn’t work here. Any ideas on how to check for a valueless disabled attribute using Puppeteer? I’m stuck and could really use some help!

I encountered a similar issue in my recent project. Here’s a reliable approach that worked for me:

const button = await page.$('button.my-button');
const isDisabled = await page.evaluate(el => {
    return el.disabled || el.getAttribute('disabled') !== null;
}, button);

This method checks both the JavaScript ‘disabled’ property and the presence of the HTML attribute. It handles various scenarios, including those with valueless attributes. Remember to wrap this in a try-catch block for error handling and ensure you’re targeting the correct button if there are multiple on the page.

Hope this helps solve your problem!

hey charlottew, i’ve dealt with this before. try using the hasAttribute method instead. something like:

const isDisabled = await button.evaluate(el => el.hasAttribute(‘disabled’));

this should work even with valueless attributes. let me know if it helps!

I’ve been using Puppeteer for a while now, and I’ve found that the most reliable way to check for a disabled button is to evaluate its CSS properties. Here’s what I typically do:

const button = await page.$(‘button.my-button’);
const isDisabled = await button.evaluate(el => {
const style = window.getComputedStyle(el);
return style.cursor === ‘not-allowed’ || style.opacity < 1;
});

This approach works well because it checks the visual state of the button, which is what matters from a user’s perspective. It’s also more robust against different ways of implementing disabled states in various frameworks.

Just make sure you’re selecting the right button if you have multiple on the page. And don’t forget to handle any potential errors!