I have a site at work that when not logged in, redirects to the wrong login page.
<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>
The actual page is loaded with a 200 OK and no Location:
header.
To remedy this, I composed a Greasemonkey script to run before pageload:
// ==UserScript==
// @name Fix buggy login redirect
// @namespace [email protected]
// @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);
My script checks if the JavaScript to redirect to the wrong page is there, then sends me off to the correct login URL.
This script works fine -- if the alert()
is there. Remove the alert()
and the page redirects to the broken login page. However, when alert()
is there, I never see the alert box, but do get redirected to the proper page.
I could leave the alert()
in, as it doesn't ever seem to run, but I'd like to remove it and still have the page redirect to my desired page.
My questions regarding this issue:
alert()
call?That code has some "race conditions". With the alert()
missing, the old JS still fires before the location.replace();
finishes.
The alert takes time to fire. With it in place, the location.replace
finishes before it can.
The correct thing is to stop the script and then fire the replace. Do that with stopPropagation
and preventDefault
. Something like so:
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);