How to make a console error when a site tries to change the location?

Viewed 78

I need to make a console error after this commands:

location = 'http://example.com/';
location.href = 'http://example.com/';

So there will be no redirect after that.

It is about the location object. No need onbeforeunload because it is a workaround (which I know) and because I need to know/see (as a variant, in console) the target url without/before redirecting, onbeforeunload can't help with this.

1 Answers

You can try this (it will be some like this)

const link = doc.getElementById("linkid"); // link
// link click event
link.addEventListener("click", (e) => {
    
    try {
    // when target changed
    if (link.href !== "your location" // (or default target)) {
        e.preventDefault(); // stops routing
        console.log(link.href); // watching navigation
     } else {// console.log(link.href)}
    }
    catch(err) {
    console.err(err.message); // displaying error message 
    alert("Error: " + err.message);
    throw err;
    }
  })
Related