MP123
MP123

Reputation: 275

Javascript Is there a way to detect a page has been requested

At the very moment an a-tag has been clicked and the browser commences to request the URL. Is there a way to detect that request and what the URL request is?

Upvotes: 4

Views: 83

Answers (2)

Webdev
Webdev

Reputation: 647

For the requested URL , you can use the code below :-


    document.referrer;

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

At the very moment an a-tag has been clicked and the browser commences to request the URL

If you are sure that only way a page (URL) will be requested is by clicking a link, then you can add an event listener to the anchor tags of the page

In pure JS

var allAnchors = document.getElementsByTagName("a");
for ( var counter = 0; counter < allAnchors.length; counter++)
{
    allAnchors[counter].addEventListener( "click", function(e){
      e.preventDefault();
      var src = this.getAttribute( "href" );
      alert( "This link was clicked " + src )
      location.href = src;
    }, false );
}

In jQuery

$( "a" ).click( function(){
      e.preventDefault();
      alert( "This link was clicked " + $( this ).attr( "href" ) );
      location.href = $( this ).attr( "href" );
} );

Upvotes: 1

Related Questions