1

Problem:

I want to track all the forwards to another page, e. g. when a user clicks on a link leading to the site https://example.com/ I want to track this event. The forward should also be tracked when calling:

location.href="https://example.com". 

The code should look something like this:

$(window).on("forward???", function(event) {
    //This is just some pseudo code
    console.log(event.href);
});

Expected Output:

The program should output the link to which is forwarded to, e. g.:

https://example.com/page1

Is it possible to track such an event using jquery or vanilla javascript?

Purpose:

I'm looking for a solution to track all forwards to another page so I don't have to implement it for each link or location.href seperately.

Philip F.
  • 1,167
  • 1
  • 18
  • 33

1 Answers1

2

You could track clicks on any a tags.

$('a').on('click', function() {
  console.log($(this).attr('href')); // or any other tracking logic

  return true; // continue with link
});
FrEaKmAn
  • 1,785
  • 1
  • 21
  • 47
  • But what if it's not a link (in the a-tag)? e. g. if I forward using javascript (maybe on the click of a button) – Philip F. Nov 26 '20 at 15:21
  • But what is the logic for the button? Buttons generally don't redirect to new page (except if part of the form). – FrEaKmAn Nov 26 '20 at 18:53
  • Suppose I have two forms on a website. Each one has a submit button. I make an ajax call on the submit and then forward to another page. I just want to log each forward. – Philip F. Nov 29 '20 at 16:08
  • Can you also share the code where you forward to another page? Are you using window.location? – FrEaKmAn Nov 29 '20 at 16:34
  • 1
    There are few options mentioned here https://stackoverflow.com/questions/3522090/event-when-window-location-href-changes But if you can control the code, why don't you call tracking code before you use location.href? – FrEaKmAn Nov 29 '20 at 17:12
  • Cause I've written quite a lot of code and don't want to update each bit. But thanks, that link helped a lot. – Philip F. Nov 29 '20 at 18:14