0

I tried to search for a similar problem but I couldn't find one. here is my problem - In my React app - I have a button that after pressing on it, it should open a new URL (in the same tab) - so far so good. I know that in the new URL there is a button with an identifier. How can I open the window and after the DOM is loaded - press the button? when I tried to use querySelect to get the button I received null but I believe it's because that the DOM was not fully loaded.

here is the onClick function:

function func(){
    newPath = '***SOME URL****';
    newWindow = window.open(newPath , "_self");
    newWindow.document
            .querySelector("*** SOME IDENTIFIER ***")
            .click();
}

Is it possible? if so, what is the best approach to handle this case? Thanks.

OA617
  • 76
  • 6
  • And what's the goal of clicking thuis button , do you have an event to be excucted ? if yes , just fire this event – Rebai Ahmed Jun 25 '20 at 08:58
  • how about `newWindow.document.addEventListener('DOMContentLoaded', ...)` ? – ccld44 Jun 25 '20 at 09:03
  • Thanks for the comments. Using "DOMContentLoaded" has no effect - it seems like the event was fired before it gets to the addEventListener. In addition, when I tried to inspect the document object of the new window it returns content that belongs to the previous URL. – OA617 Jun 25 '20 at 10:13
  • if the source of '***SOME URL****' is react too, you could call click() event in didMount or useEffecte when open url and did mounted element the click event fire. – r.a.shehni Sep 19 '22 at 07:04
  • @OA617 : or may you could use document.addEventListener('readystatechange', (event) => { // add addEventListener with event }); – r.a.shehni Sep 19 '22 at 07:46

1 Answers1

0

See the answer on https://stackoverflow.com/a/36096571/8672333.

You can do something like:

function func(){
    newPath = '***SOME URL****';
    newWindow = window.open(newPath , "_self");

    document.addEventListener("DOMContentLoaded", function() {
       // Your DOM should be fully loaded here
       newWindow.document
            .querySelector("*** SOME IDENTIFIER ***")
            .click();
    });
}
  • Thanks for your reply! Using "DOMContentLoaded" has no effect - it seems like the event was fired before it gets to the addEventListener. In addition, when I tried to inspect the document object of the new window it returns content that belongs to the previous URL. – OA617 Jun 25 '20 at 10:14