捕获/覆盖 Javascript 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7790026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:19:58  来源:igfitidea点击:

Catching/Overriding a Javascript redirect

javascripthtmldomredirecthref

提问by Trevor

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

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

For example:

例如:

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

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

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

回答by Darin Dimitrov

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:

AFAIK 您可以捕获此事件,但不能更改目标 url。您只能提示用户是否要取消重定向。为此,您可以订阅before unload 事件

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?';
};

回答by alex

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

您可以尝试使用,__defineSetter()__但它可能不适用于宿主对象。

回答by jfriend00

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;
}