【问题标题】:Greasemonkey-issued redirect only works if alert() is called after the redirection line仅当在重定向行之后调用 alert() 时,Greasemonkey 发出的重定向才有效
【发布时间】:2016-10-19 02:25:48
【问题描述】:

我有一个工作站点,当未登录时,它会重定向到错误的登录页面。

<html>
  <head>
    <meta name="robots" content="noindex,nofollow">
    <script type="application/javascript">
      window.location.href = '/access/login?return_to=' + encodeURIComponent(window.location.href);
    </script>
  </head>
</html>

实际页面加载了 200 OK 并且没有 Location: 标头。

为了解决这个问题,我编写了一个 Greasemonkey 脚本在页面加载之前运行:

// ==UserScript==
// @name        Fix buggy login redirect
// @namespace  apburk@example.com
// @description Fixes the buggy redirect that redirects to the wrong login page
// @include    https://internal.domain/*
// @version    1
// @grant      none
// @run-at document-start
// ==/UserScript==
window.addEventListener('beforescriptexecute', function(e) {
if (document.getElementsByTagName("script")[0].text.trim() === "window.location.href = '/access/login?return_to=' + encodeURIComponent(window.location.href);") {

window.location.replace('https://example.com');
alert(" ");
}

}, true);

我的脚本检查是否存在重定向到错误页面的 JavaScript,然后将我发送到正确的登录 URL。

这个脚本工作正常——如果alert() 在那里。删除alert(),页面重定向到损坏的登录页面。但是,当alert() 在那里时,我从来没有看到警告框,但 确实 会被重定向到正确的页面。

我可以保留alert(),因为它似乎永远不会运行,但我想删除它并仍然让页面重定向到我想要的页面。

我关于这个问题的问题:

  • 为什么会出现这种情况?是否涉及时间问题?
  • 如果没有无用的alert() 电话,我怎样才能使其正常工作?

【问题讨论】:

    标签: javascript redirect greasemonkey


    【解决方案1】:

    该代码有一些“竞争条件”。在alert() 丢失的情况下,旧的JS 仍然会在location.replace(); 完成之前触发。
    警报需要时间才能触发。有了它,location.replace 就可以提前完成。

    正确的做法是停止脚本,然后触发替换。使用stopPropagationpreventDefault 进行操作。像这样:

    window.addEventListener ('beforescriptexecute', function (e) {
        if (document.getElementsByTagName ("script")[0].text.trim()
            === "window.location.href = '/access/login?return_to=' + encodeURIComponent(window.location.href);"
        ) {
            e.stopPropagation ();
            e.preventDefault ();
            window.location.replace ('https://example.com');
        }
    }, true);
    

    【讨论】:

    • 啊!!这就解释了;试过了,效果很好。我以前不知道 stopPropagation,也不知道 preventDefault。感谢您的宝贵时间!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2018-12-29
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多