简体   繁体   English

Javascript:刷新页面的现代工作方法重定向到另一个位置

[英]Javascript: Modern working approach to refresh the page redirects to another location

I have tried some answers on SO, but they are old and no longer work, or are blocked by the browser.我已经尝试了一些关于 SO 的答案,但它们很旧并且不再起作用,或者被浏览器阻止。

I have a login, and a separate login failed page (separate for a good reason, please don't say make them the same page).我有一个登录名和一个单独的登录失败页面(分开是有充分理由的,请不要说使它们成为同一页面)。

If the user is shown the failed login page, and they hit refresh, I would like to go to the login page, not refresh the failed login page.如果用户显示登录失败页面,并且他们点击刷新,我想 go 到登录页面,而不是刷新失败的登录页面。

Existing answers go something like this:现有答案 go 是这样的:

<script type="module">
    function redirect()
    {
        window.location.href="/login/";
        return true;
    }
    window.addEventListener('beforeunload', redirect);
</script>

Not ideal, but instead of catching the reload before navigating away, catch the reload at the start of the page:不理想,但不是在离开之前捕获重新加载,而是在页面开头捕获重新加载:

Reload detection code from: https://stackoverflow.com/a/53307588/5506400重新加载检测代码来自: https://stackoverflow.com/a/53307588/5506400

<script type="module">
    const pageAccessedByReload = (
    (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance
        .getEntriesByType('navigation')
        .map((nav) => nav.type)
        .includes('reload')
    );
    if (pageAccessedByReload) {
        window.location.href="/login/";
    }
</script>

let me know this will help or not, use type value to check for reload让我知道这是否有帮助,使用类型值检查reload

 // Use getEntriesByType() to just get the "navigation" events var entries = performance.getEntriesByType('navigation'); for (var i = 0; i < entries.length; i++) { console.log('= Navigation entry[' + i + ']'); var p = entries[i]; // dom Properties console.log( 'DOM content loaded = ' + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart) ); console.log('DOM complete = ' + p.domComplete); // other properties console.log('type = ' + p.type); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM