0

Environment: Chrome, a simple Web Portal

I'm trying to do a simple browser automation.

In a HTML table, 1. Clicks the first link, 2. Change the dropdown value and 3. click Submit.

The code after button click is not executed, as the page loads after the button click.

var tbl = document.getElementById("incident_table")
tbl.rows[2].cells[2].getElementsbyClassName("linked")[0].click()
// below code is not executing, as the above click loads the page
document.getElementById("incident.state").selectedIndex = 1
document.getElementById("sysverb_update").click()

I can able to run the last 2 lines of code separately in console, it works.

But when executing as a snippet it didnt

enter image description here

Manivannan Nagarajan
  • 1,019
  • 1
  • 9
  • 14
  • You open tag with `"` and close with `'` in line `document.getElementById("incident.state').selectedIndex = 1`, fix it and all work. – Simone Rossaini Nov 26 '21 at 07:19
  • Hi @SimoneRossaini, Thanks for pointing out the typo. it was correct in the actual code. It just the snippet stop working after page reloads. Page was reloaded at Line 2, so Line 4 and 5 are not executed. – Manivannan Nagarajan Nov 27 '21 at 13:11

1 Answers1

1

this post is very similar to your question: preventDefault() on an <a> tag

what you want to do is prevent the default action of the javascript click event.

What you may also do is:

tbl.rows[2].cells[2].getElementsbyClassName("linked")[0].addEventListener('click', ()=>{
    preventDefault();
    //write here what should happen instead
    });

What this will do is prevent the default action "reload site" from happening

Edit: What i mean in the comment is the following:

if(localStorage.getItem("firstPartComplete") === null){
   //do first part
   //set completion status in localStorage
   localStorage.setItem("firstPartComplete", true);
}else{
   // do second part
   localStorage.removeItem("firstPartComplete");
}
Hkrie
  • 117
  • 5
  • Hi @Hkrie, I want the page to be loaded. 'incident.state' dropdown will only appear after the page reloads. so I want to execute the code continuously despite of page reloads. I tried await/async/sleep/setTimeout/setInterval nothing works. Once page reloads the snippet stops. – Manivannan Nagarajan Nov 27 '21 at 13:10
  • @ManivannanNagarajan you could work with an if/else statement and cookies or the localStorage. So that you execute the first part of the code, then set an item in localStorage and then after the site refreshes you execute the second part of your code by checking if the cookie/item in localStorage is set. – Hkrie Nov 27 '21 at 15:43