JavaScript - 在没有用户干预的情况下停止重定向并获取目的地 URL

JavaScript - Stop redirection without user intervention and get destination URL

我想 运行 网页中的一些 JS,这样我就可以单击将带我到另一个网页的元素并做两件事:

  1. 获取目的地URL。
  2. 停止重定向。

到目前为止,我阅读了有关添加事件侦听器以停止重定向的信息:

window.addEventListener('beforeunload', function (e) {
    // Cancel the event
    e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
    // Chrome requires returnValue to be set
    e.returnValue = '';
});

但总是弹出窗口,我无法确定目标地址。

编辑:

我能够通过拦截 XMLHttpRequests 从微服务中获取目的地 URL,所以第一个问题就解决了...重定向仍然是一个问题。

const xhrOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
    if (method === "GET") {
        const urlQuery = "some_discrimination_factor";
        const urlPropertyName = "redirection_url";
        if(url.endsWith(urlPropertyName)) {
            this.onload = function(){
                const response = JSON.parse(this.responseText);
                if (response.hasOwnProperty(urlPropertyName)) {
                    console.log(response[urlPropertyName]);
                }
            };
        }
    }
    xhrOpen.call(this, method, url, async, user, pass);
};

这是同样的事情,但使用 DOM 2 级事件:

let xhrListener; //use only to avoid multiple listeners error while debugging
const xhrOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
    if (method === "GET") {
        const urlQuery = "some_discrimination_factor";
        const urlPropertyName = "redirection_url";
        if(url.endsWith(urlPropertyName)) {
            if (xhrListener) { //use only to avoid multiple listeners error while debugging
                this.removeEventListener("readystatechange", xhrListener);
            }
            this.addEventListener("load", function nonAnonymWrap(e){
                xhrListener = nonAnonymWrap;//use only to avoid multiple listeners error while debugging
                const response = JSON.parse(this.responseText);
                if (response.hasOwnProperty(urlPropertyName)) {
                    console.log(response[urlPropertyName]);
                }
            });
        }
    }
    xhrOpen.call(this, method, url, async, user, pass);
};
<a href="to_other_page" id="myEle1">CLICK ME</a>
var dom = document.getElementById('#myEle1');
dom.addListener('click', function($e){
  $e.preventDefault(); // stop <a> tag behavior
  var url = dom.href; // the url you want
})

像这样?

奥卡姆剃刀:

Entities should not be multiplied without necessity.

作为 JavaScript 的兔子洞的新手,我开始大量使用 XMLHttpRequest,但显然一些更简单的东西对我来说就足够了:

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