I am working on a simple script that loops through all elements on a page and shares them in vanilla JavaScript. Here is what I have so far
var buttons = document.getElementsByClassName('share-gray-large'); for(var i=0; i<buttons.length; i++){ buttons[i].click(); document.getElementsByClassName('internal-share__link')[0].click(); } The share-gray-large button is the class of the "share" buttons. Once the first share button is clicked, a modal appears that asks the user where they want to share the items to. I need to click the first item in the modal with class name internal-share__link. The problem that I am running up against is the fact that the last line of my code results in the following error
Uncaught TypeError: Cannot read property 'click' of undefined which makes sense, as the modal hasn't appeared yet at the time of the second click() function being called. I need to wait for the element to appear, then click it, then wait until the modal disappears to share the next item. I've looked into async/await functions, setTimeout(), and the solutions from similar StackOverflow questions. I adapted this secondary solution
var waitForEl = function(className, callback) { if (document.getElementsByClassName(className).length) { callback(); } else { setTimeout(function() { waitForEl(className, callback); }, 100); } }; var buttons = document.getElementsByClassName('share-gray-large'); for(var i=0; i< buttons.length; i++){ waitForEl('share-gray-large', function() { document.getElementsByClassName('share-gray-large')[i].click(); }); waitForEl('internal-share__link', function() { document.getElementsByClassName('internal-share__link')[0].click(); }); } which kind of works, but I believe that it actually ends up sharing the last item multiple times instead of sharing all of them in order. I ran into this issue of needing to wait for a button to appear as well with a different project, so any help would be greatly appreciated!
TL;DR I'm working on projects with the following sequence of steps. Using a page with 3 items that need to be shared:
- Click "share" on first button
- Wait for confirmation button to appear in a modal
- Click confirm
- Wait for modal to disappear
- Click "share" on second button
- Repeat steps 2-4
- Click "share" on third button
- Repeat steps 2-4
How do you do this in VanillaJS?
https://stackoverflow.com/questions/66718421/how-do-you-repeatedly-click-two-buttons-when-you-have-to-wait-for-the-second-but March 20, 2021 at 01:06PM
没有评论:
发表评论