0

My Application has page that displays the details in a list view. On clicking on the list item it will drill down to the page which shows its respective details.

I need to navigate from the details page to the list page using the default back button in mobile or browser, but the same back button should not work when I click on it in the list view page.

I tired to prevent the default action of the back button by adding the below code in the JS of that list page. However the back button is disabled for the whole application.

document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown(e) {
  e.preventDefault();
  // alert('Back Button is Pressed!');
}

Could anyone help me to solve this issue. Thanks in Advance

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Janaki Narayanan
  • 523
  • 6
  • 24
  • 2
    You can't reliably disable the back button. If you need to do this then it points to a flaw in your site architecture. – Rory McCrossan Sep 21 '18 at 10:32
  • Possible duplicate of [how to stop browser back button using javascript](https://stackoverflow.com/questions/12381563/how-to-stop-browser-back-button-using-javascript) – belvederef Sep 21 '18 at 11:11
  • Can your `onBackKeyDown` method inspect the current URL, and only call `preventDefault` if it matches a specific URL? – Alex Peters Sep 21 '18 at 13:01

2 Answers2

1

To handle the back button behavior (simulating disable) you have to handle the navigation and a variable to know when navigation is permitted.

I made a page to show how, it works with browsers back button and Android back button.

The variable disableBackButtonInThisPage is initially true, so navigation is not permitted.

A "Toggle disable" button changes the disableBackButtonInThisPage value, so when it is false, navigation is permitted.

<!DOCTYPE html>
<html lang="en">

<head>
    <script>
        history.pushState(null, null, location.href);
        var disableBackButtonInThisPage = true;
        window.onpopstate = function () {
            if (disableBackButtonInThisPage) {
                history.go(1);
            }else{
                history.go(-1);
            }
        };
        function toggleDisable() {
            disableBackButtonInThisPage = !disableBackButtonInThisPage;
            alert("Disable back button is: " + disableBackButtonInThisPage);
        }
    </script>
</head>

<body>
    <h1>Back button demo</h1>
    <p>Click browser back button or tap Android back button.</p>
    <button onclick="toggleDisable();">Toggle disable</button>
</body>

</html>
David Hernán
  • 61
  • 1
  • 3
0

you must manage with some variable in which section you are and update it every time you change, in this case I do it with 'pagenow'

<button data-bind="enable: pagenow()!='listpage'">Back</button>