简体   繁体   中英

How to click an element in javascript using click() and then execute another function?

I am trying to create an extension where I open a chrome tab and then click a button in that DOM and then close that tab.

So below is JS file in which the function gets executed once the window gets loaded. But I don't know a way to add a callback to click function

window.onload = function() {
   document.getElementsByClassName(<className>).click()
   window.close()
}

Based on your comment "I want to click add to cart button and wait for the item to get added to the cart and then close the window" I think you are looking at this wrong.

Your onload function should perform the click.

window.onload = function() {
   document.getElementsByClassName(<className>).click()
}

Then some other function should close the window after detecting the item was added to the cart

[some other event] = function() {
   window.close()
}

The some other event could be detecting onchange of some other element that shows the item in the cart. It's hard to know without seeing the page.

If it needs to be independent of the design of the website, I don't have a good suggestion. Even with a "callback to click function", every website might handle the click differently. Some may have a submit button that does a HTTP POST. Others might be an Ajax call that is either synchronous or asynchronous. Others might use javascript to update some other elements of the DOM, which themselves trigger an event that triggers a click. These are just examples and there are likely other cases. Detecting the "click" won't detect the item in the cart.

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