0

I'm using this javascript code:

document.getElementsByName("commit")[0].click();

to perform a click on a button, the problem is that when I send the command sometimes the page is't loaded , so it can't be clicked . So how i can perform the click until it actually happens ? i have tried something like this:

if (document.readyState === 'complete') { //don't work
document.getElementsByName("commit")[0].click();

}

but it doesn't work. (I can't use jquery, cause I'm on a chrome extension)

droidBomb
  • 794
  • 3
  • 8
Marià
  • 135
  • 9
  • Something like this: https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-when-t – devzero Sep 20 '18 at 20:28
  • Give something like this a shot: `document.addEventListener("DOMContentLoaded", function(event) { //code here });` This is the equivalent to jQuery `document.ready` – EliTownsend Sep 20 '18 at 20:28
  • The addEventListener isn't 100% cross browser – devzero Sep 20 '18 at 20:30
  • 1
    @devzero That is a good point. It is supported for Chrome though so that is why I thought it could be used for a Chrome Extension – EliTownsend Sep 20 '18 at 20:34
  • @EliTownsend i have tried but it doesn't work. (document.addEventListener("DOMContentLoaded", function(event) { alert("aaaa"); });) it doesn't work unfortunatly – Marià Sep 20 '18 at 20:35
  • i have tried also to put in chorme console : it results : undefined – Marià Sep 20 '18 at 20:36
  • 1
    @Marià You have an extra `;` Make the code this and it works `(document.addEventListener("DOMContentLoaded", function(event) { alert("aaaa"); }))` – EliTownsend Sep 21 '18 at 12:38

3 Answers3

0

Firing it on the DOMContentLoaded event should do the trick

document.addEventListener('DOMContentLoaded', function() {
    document.getElementsByName("commit")[0].click();
})
MPawlak
  • 568
  • 5
  • 14
  • i have tried what you write , and i have also added an alert , but it does nothing even the alert – Marià Sep 20 '18 at 20:34
  • even if i put it in the chrome console it says: undefined – Marià Sep 20 '18 at 20:36
  • Well putting it in the console will return undefined since this isn't returning anything. See this question, it looks like updating the manifest will work, can you try that? https://stackoverflow.com/a/5082307/4869078 – MPawlak Sep 20 '18 at 20:40
0

Try this

window.onload = function() {
   console.log("page loaded");
   //your code here
}

I would also be sure that you are including your javascript files at the bottom of the page and not the top.

Jake
  • 676
  • 6
  • 20
  • it doen't return any arror but it doesn't work.. i have tried window.onload = function() { console.log("page loaded"); alert("loaded"); //your code here } but nothing – Marià Sep 21 '18 at 08:21
0

Try this code:

document.querySelector('#myBtn').addEventListener('click', function () {
 // do some stuff here
});
jess
  • 2,376
  • 1
  • 7
  • 23