I am trying to disable the browser back button functionality on a page (bad UX, I know all of the implications of this action) using a script referenced here but the script only seems to work after the user has somehow interacted with the page (eg. clicked on the tab).
If the user navigates to the page and clicks on the back button the script doesn't seem to be working. I am not trying to fix it because the functionality it provides is good enough for our usecase but I am curious as to why this script doesn't seem to work until the user interaction.
The script was tested and the behaviour was observed on Chrome Version 93.0.4577.82 and Edge Version 95.0.1020.53
<script>
(function (global) {
if(typeof (global) === "undefined") {
throw new Error("window is undefined");
}
var _hash = "!";
var disableBack = function () {
global.location.href += "#";
global.setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _hash) {
global.location.hash = _hash;
}
};
global.onload = function () {
disableBack();
document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
e.stopPropagation();
};
};
})(window);
</script>