Click event not triggering for every iteration of for loop - javascript

I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.
Manually clicking 10 times will generate 10 tabs. But see the following code:
for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}
I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see
Edit:
#Jesse
See my utility full code:
var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
// console.log(`${i.getFullYear()}-${i.getMonth()}`);
// var dd=`${i.getFullYear()}-${i.getMonth()}`;
var dd=new Date(i).toISOString().substr(0,7);
console.log(dd);
document.querySelector("input#picker.form-control").value=dd;
var type='Supplementary'
document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
document.querySelector('#reg1').click();
}

Somehow you have to execute the subsequence clicking in an asynchronous manner. I got this work by this:
let i=0;
(function doClick(){
document.querySelector('#reg1').click();
i++;
if(i<10) setTimeout(() => doClick());
})()
Another approach using async function:
(async function doClick() {
for(let i=0;i<10;i++) {
document.querySelector('#reg1').click();
await new Promise(setTimeout);
}
})()

I just figured out that my browser's popup blocker is stopping the subsequent tabs from being opened.
Try turning off your popup blocker. I was able to trigger the behavior you're after with mine off.
It works when you click it because it's a user interaction, so the blocker assumes it's something you're actively trying to do. If you trigger it programmatically, repeatedly, it gets blocked. This makes sense given that one of your browser's popup blocker's primary functions is to prevent sites from trapping you in infinite popup hell.

It's because you're using the same ID. Either switch to using a class or change the ID names so they aren't identical.

Related

How can I click 2 buttons simultaneously?

I work in a Call center (ticket based Support) and for me to get a ticket I need to click on 2 Buttons. the one that opens the tickets section, and the one that actually gets me a ticket. After i click on the Get_ticket class, the ticket box closes. So i need to start again to click on the "Tickets" Button, and then on Get_Ticket. Tickets button -> Get_ticket. And repeat and repeat. I want to tell Google console to help me with this. I found a way but it's not very friendly. I tried with the button.click function at a different interval but it's not working...If i put the function separately, it's working, but when I put the functions at the same time in Console, it's not working. Can you please give me an advice ? Those are the functions:
1.(click on TICKETS)
var button = document.getElementsByClassName("_1f8o8ru7")[0];
setInterval(function(){button.click();},2000);
2.(Click on GET TICKET)
var button2 = document.getElementsByClassName("_sl2x43m")[0];
setInterval(function(){button2.click();},2500);
The second interval should be added inside the first interval. I also recommend to use setTimeout, instead of setInterval.
setInterval(function(){
var button = document.getElementsByClassName("_1f8o8ru7")[0];
button.click();
setInterval(
function(){
var button2 = document.getElementsByClassName("_sl2x43m")[0];
button2.click();
},2500);
},2000);
After you figure it out, you can save your code in a js file: my_script.js and use Chrome extension JS Injector to automatically inject it in your page, without needing to use Chrome DEV Tools.
you need to call first button click on click of first button call another method on given timeout
so first time 1 button is clicked after on click of first button call another button method with 500 timeouts will be ok no need to do 2000 or 2500 timeout

Testcafe .presskey for multiple presses

I'm trying to write TestCafe Javascript to test a webpage using the keyboard as sole navigation (i.e. 'tabbing through the options').
TestCafe runs these tests, but they run extremely fast (5 seconds max), and nothing happens on the screen. So I'm wondering if it's even actually working.
On top of that, I'm trying to find a way to DRY out my code. From what I read in the docs, each time I want a key pressed, I need to call .pressKey('tab'). If I need to hit 'tab' 5 times in a row, I have 5 lines of that in my code. Is there any way to eliminate this unnecessary repetition?
Thanks!
TestCafe sets focus to the next element on the page when the .pressKey('tab') action is called. To make your code cleaner, you can pass several keys separated with spaces to the pressKey action.
I've created a simple example for this stackoverflow page:
import { Selector } from 'testcafe';
fixture `stackoverflow`
.page `https://stackoverflow.com/questions/46612440/testcafe-presskey-for-multiple-presses`;
test('tab', async t => {
await t
.click(Selector('#search').find('[name="q"]'))
.pressKey('tab tab tab tab tab tab tab tab tab tab tab tab tab tab');
});
Here is a screencast that demonstrates how it works (I've set the test run speed to 0.5 via the --speed option): https://www.screencast.com/t/dERD60nGc4f
If you want to slow it down to visually check, you can interleave calls to wait(x)
await t.pressKey(TAB);
await t.wait(800);
await t.pressKey(TAB);
await t.wait(800);
etc.

Continuing functions for chrome extensions-javascript

so I am working on a really small chrome extension. There is a webpage and I want to click the buttons on this webpage. After I click all of them I want to click the next page button and keep doing the same thing.
I have no problem finding the buttons or the nextpagebutton. I am also able to do it using setInterval functions but I feel like it is kind of a hacky way to do this.
The below code is what I have so far
function clickButtons(){
var followButtons = $('.buttonClass');
var numberOfButtons = followButtons.length;
for(var i=0; i<numberOfButtons; i++){
followButtons[i].click();
}
setTimeout(nextPage, 500);
}
function nextPage(){
var nextPageBtn = $('.nextPageButtonClass');
nextPageBtn.click();
setTimeout(clickButtons,500);
}
so my question is
1. My for loop to click all the buttons is not working. Is there a better way to click every button class?
2. I need to call the second function after the first one. And when the second one is finished, I need to call the first one again and they must follow each other constantly. I tried setting a timeout and calling the other one ın both functions. But it is not working. How can I do this?
This code basically doesn't do anything. And I have been scratching my head. Sorry I am a huge javascript noob

Click Anywhere Pop Up Windows Once pervisit?

Anyone can help how to open new windows when clicked anywhere but only once pervisit.
Example, you visit google.com and click anywhere there, and new window will open but only once, second click will not open windows.
Site example : http://afowles.blogspot.com
My script is
Function popup() {
window.open ("http://www.stackoverflow.com","popup","menubar=1,resizable=1,width=450,height=550");
And then put onclick="popup()"
In body.
Code above show new windows every single click on the site. What should i do to make it only show once?
Set a global variable
a=1;
then in function check for variable's value. After windows.open is executed, change the global variable's value, so that windows.open will not be executed again.
Code:
<script>
var a=0;
function popup() {
if(a==0){
window.open ("http://www.stackoverflow.com","popup","menubar=1,resizable=1,width=450,height=550");
a++;
}
}
</script>
Firstly you will need to define to yourself what a visit consists of, i.e. once per day, week, or each time a users lands on your site, every page loaded, etc.
Assuming you want some persistence for your users while they browse, what you need to do on your site is set a condition to be evaluated prior to the first click and if the result indicates a users' first visit then open the page. At the same time, set a value to be checked next time (and most likely all subsequent clicks based on your current implementation). LocalStorage or cookies would be your best options for this.
I would set up something along the lines of:
//check page is loaded
if (cookie.firstVisit) {
//add click event listener
} else {
//set cookie.firstVisit to false
//remove click event listener
}
Instead of spelling out how to do this with cookies here, have a look at this article which explains it all: How to set/unset cookie with jQuery?
Lastly, opening a new window when someone clicks anywhere on your page without them explicitly wanting that action perform is considered bad practice in most scenarios. However, I do not know your situation so this may be the best course of action but thought it was worth mentioning.

JavaScript: Reload page AFTER function has finished executing in infinite loop

I am creating a Google Chrome extension. This extension uses JavaScript to click all instances of a "follow" button on a specific web page, reloads the page, then performs the function again, in an infinite loop. It finds these follow buttons by fetching an attribute where the attribute "class" = "follow".
I am having trouble getting it to work properly, though. Instead of clicking all instances of the follow button and then refreshing, it just refreshes after one instance has been clicked.
I have tried removing the timer completely. That resulted in the script not working at all.
I removed the page refresh, and the script worked as expected, but obviously only for one instance of the page load.
Here is my code:
function tr_f() {
var followlinks = [];
for (var i=0; i < document.links.length; i++) {
if (document.links[i].getAttribute("class")=="follow"){
followlinks[followlinks.length] = document.links[i];
}
}
for (var i=0; i<followlinks.length; i++) {
var rrr=followlinks[i].onclick();
}
window.setTimeout( function(){document.location.reload();}, 5000 );
} tr_f();
There is also a button on this webpage with the "reload" class that reloads the page. Perhaps this could be implemented within the function and is only clicked once all instances of the "follow" button have been clicked, to make it work as expected. For informational purposes, we assume that the number of follow buttons on the page in question is unknown.
Any and all help regarding this will be greatly appreciated.

Categories

Resources