Here is another way to proceed. Instead of just trying to avoid the Back button functionality (which doesn't work reliably) we can add short SessionStorage conditions.
Say we have three different pages (page1, page2, and page3). On each page we got a link to click to acceed to the next one and we don't want the user to be able to go back to the previous page.
On the first page (page1.html) we create an SI (sessionStorage Item) with a dummy "prev" code and another one with "page1" code (SI "now"):
PAGE 1 <button onclick="goto()">PAGE 2</button>
-------------------
let thispage = '1' // Or 123456 if preferred or make sense
// You can replace this fixed 'thispage' value on each page with a script counting the clicks
// or any other way to increase its value, i.e., thispage++
// or what you want, even counting the url.length (lol)
sessionStorage.setItem('prev', '0') // Dummy code
sessionStorage.setItem('now', thispage)
// You can here make this page unreachable with page2/page3 SI same conditions
function goto(){
window.location = "page2.html"
}
On page2.html we use the usual NoBack script (if it works) and update SIs only if we're coming from page1:
PAGE 2 <button onclick="goto()">PAGE 3</button>
-------------------
// If it works, let it work :-)
history.pushState(null, null, location.href);
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
// else
let thispage = '2' // 456789
let thisprev = sessionStorage.getItem('now')
if(sessionStorage.getItem('prev')==thispage) {
console.log('USER is back on PAGE 2')
setTimeout(function() { goto() }, 1000); // Remove log + setTimeout
}
if(thisprev !== thispage) {
if(thisprev < thispage) {
console.log('USER is coming from PAGE 1')
sessionStorage.setItem('prev', thisprev)
sessionStorage.setItem('now', thispage)
}
else {
console.log('USER try to reload this page')
setTimeout(function() { goto() }, 1000);
}
}
function goto(){
window.location = "page3.html"
}
And on page3.html:
PAGE 3 <button onclick="goto()">BACK TO PAGE 1</button>
-------------------
history.pushState(null, null, location.href);
history.back();
history.forward();
window.onpopstate = function () {
history.go(1);
};
let thispage = '3' // 999999
let thisprev = sessionStorage.getItem('now')
if(sessionStorage.getItem('prev') == thispage) {
goto()
}
if(thisprev !== thispage) {
if(thisprev < thispage) {
sessionStorage.setItem('prev', thisprev)
sessionStorage.setItem('now', thispage)
}
else {
goto()
}
}
function goto(){
window.location = "page1.html" // Reinit test
}
The advantage is that even if the user manually reloads the previous page (if he had time to see and remember the URL) it still works. It was not tested on all devices, but seems to work fine on Firefox + Chrome + Edge Windows 10 and Firefox + Chrome on OS X.