Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a new page is being loaded

Tags:

javascript

Is there a way to detect via JavaScript, whether a new page is being loaded. Let me give you an example.

Another page is being loaded after I on this link:

<a href='http://google.com/'>Click here</a>

There's no page load after I click here:

<a href='#anchor'>Click here</a>

No page load here either:

<a href='javascript:void(0);'>Click here</a>

Yep, that's a page load. But the href attribute is not URL of the page being loaded:

<a href='javascript:void(document.location="http://google.com/");'>Click here</a>

This has URL in href, but it will not load a page. The onclick attribute is here just to illustrate the problem. In real world, the onclick event would probably by attached by event listener and canceled by event.preventDefault() somewhere else in the code:

<a href='http://google.com/' onclick='return false;'>Click here</a>

Now imagine, that the next page takes long time to load. What I need is a way to detect whether a new page is being loaded, after I click on the link. Or after a form submit. Or after any action that can result in page load. I know which actions to watch, but I can't be sure if they necessarily trigger the page load.

Is it even possible? If so, how?

Thanks.

like image 398
Fczbkk Avatar asked Feb 14 '23 14:02

Fczbkk


1 Answers

The beforeunload event is probably what you are looking for. Such event handlers are usually used, for example, to prevent user from accidentally leaving a page with a filled form, by showing a confirmation dialog with a custom text message.

like image 73
Marat Tanalin Avatar answered Feb 16 '23 05:02

Marat Tanalin