php_nub_qq
php_nub_qq

Reputation: 16055

Javascript detect URL the user is leaving to

My website, as most websites today, uses the same template for most of its pages and I am building a system that allows for ajax to load only page content without reloading the whole template. For the purpose I'm looking for a method that fires before the browser is redirected to another page. Something like onbeforeunload but I also need to know the location of the redirect, is there such a thing?

I need to catch link clicks, back button clicks, forward button clicks as well as manual redirects like window.location = url

Upvotes: 1

Views: 655

Answers (1)

Quentin
Quentin

Reputation: 943996

There is no direct way to find out what URL the user is leaving the page for.

You would need to bind event handlers to the various different things that the user can use to leave the current page.

For links, you can bind a click event handler and then examine the href attribute.

For forms, you can bind a submit event handler and then collect the form data and examine the action and method.

For the back button you can bind a popstate event handler (which you could use in conjunction with pushState and friends).

You, obviously, couldn't detect where the user was going if they used a bookmark or just typed a new address into the address bar.

Upvotes: 3

Related Questions