捕获/覆盖 Javascript 重定向

发布于 2024-12-10 19:30:47 字数 154 浏览 0 评论 0原文

我将如何覆盖/捕获 JavaScript 重定向?

例如:

window.location.href="http://example.com";

值“http://example.com”将被捕获并可能被更改。

How would I go about overriding/catching a javascript redirect?

For example:

window.location.href="http://example.com";

The value "http://example.com" would be caught and maybe altered.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苏别ゝ 2024-12-17 19:30:47

AFAIK 您可以捕获此事件,但无法更改目标 url。您只能在用户想要取消重定向时提示用户。为此,您可以订阅 卸载事件之前

window.onbeforeunload = function (e) {
    var e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Are you sure you want to leave the site?';
    }

    // For Safari
    return 'Are you sure you want to leave the site?';
};

AFAIK you can catch this event but you cannot alter the target url. You could only prompt the user if he wants to cancel the redirect. For this you could subscribe to the before unload event:

window.onbeforeunload = function (e) {
    var e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Are you sure you want to leave the site?';
    }

    // For Safari
    return 'Are you sure you want to leave the site?';
};
百善笑为先 2024-12-17 19:30:47

You could try using __defineSetter()__ but it may not work on host objects.

心舞飞扬 2024-12-17 19:30:47

找到所有使用 this: 的代码

window.location.href="http://example.com";

并将其更改为:

openURL("http://example.com");

然后,实现此函数,您可以在其中控制重定向:

function openURL(url) {
    // examine url and decide if you want to modify it
    window.location = url;
}

Find all code that uses this:

window.location.href="http://example.com";

and change it to this:

openURL("http://example.com");

Then, implement this function where you can control the redirect however you would like:

function openURL(url) {
    // examine url and decide if you want to modify it
    window.location = url;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文