I’m working with a Chrome extension that does auto-refreshes. It has a feature to click a button after each refresh. I’ve set it up to click the first button, but now I need help clicking a second button that shows up after the first one.
The extension lets me add custom JavaScript code. I’m not sure how to write the script to find and click this second button. Here’s what the button looks like in the HTML:
<button _ngcontent-xwg-c7="" class="btn btn-success btn-block">Ticket</button>
Can anyone help me figure out the JavaScript to make this work? I’m pretty new to coding, so a simple explanation would be great. Thanks!
hey there! for finding that button, u could try using document.querySelector() with the class names. something like:
let secondButton = document.querySelector(‘.btn.btn-success.btn-block’);
if (secondButton) {
secondButton.click();
}
hope this helps! lmk if u need more info
I’ve worked on a few Chrome extensions, and here’s a trick I’ve found useful for situations like this. Instead of relying on specific class names, which can sometimes change, you might want to try targeting the button by its text content. Here’s a script that could work:
function clickTicketButton() {
const buttons = Array.from(document.getElementsByTagName(‘button’));
const ticketButton = buttons.find(button => button.textContent.trim() === ‘Ticket’);
if (ticketButton) {
ticketButton.click();
} else {
console.log(‘Ticket button not found’);
}
}
setTimeout(clickTicketButton, 1500);
This approach is more flexible and might be more reliable if the site’s HTML structure changes. The setTimeout ensures the button has time to appear after the first click. Adjust the delay as needed based on how quickly the second button typically shows up on your target site.
Remember to test this thoroughly on different pages where you’ll be using it. Good luck with your extension!
I’ve dealt with similar situations in Chrome extensions before. Here’s a more robust approach you might consider:
function clickSecondButton() {
const buttons = document.querySelectorAll('button.btn.btn-success.btn-block');
if (buttons.length > 1) {
buttons[1].click();
} else {
console.log('Second button not found');
}
}
setTimeout(clickSecondButton, 2000);
This script waits 2 seconds after the page loads (adjust as needed) to ensure the second button has appeared. It then selects all matching buttons and clicks the second one if it exists. The delay and error logging can help troubleshoot timing issues. Remember to test thoroughly, as button behavior can vary between sites.