Skip to content Skip to sidebar Skip to footer

Javascript - Stop Redirection Without User Intervention And Get Destination Url

I want to run some JS in a webpage so I can click elements that will take me to another webpage and do 2 things: Get the destination URL. Stop the redirection. So far I read abou

Solution 1:

<ahref="to_other_page"id="myEle1">CLICK ME</a>
var dom = document.getElementById('#myEle1');
dom.addListener('click', function($e){
  $e.preventDefault(); // stop <a> tag behaviorvar url = dom.href; // the url you want
})

like this?

Solution 2:

Ockham's razor:

Entities should not be multiplied without necessity.

Being new to JavaScript's rabbit hole I started going heavy on XMLHttpRequest but apparently something simpler was sufficient for my case:

//backup original function in case redirection is needed laterconst windowOpen = window.open;
let isRedirectionEnabled = false;
window.open = function() {
    //destination URL obtained without redirectionlet targetUrl = arguments[0]; 
    console.log(targetUrl);
    if(isRedirectionEnabled) {
        windowOpen.apply(this, arguments);
    }
};

Post a Comment for "Javascript - Stop Redirection Without User Intervention And Get Destination Url"