Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop jQuery Mobile using hash navigation and html5 history?

I'm making a little web app with jQuery Mobile and I was to stop the address bar being updated. This is so the back button on phones no longer works and a user cannot jump into the middle of the app via a URL.

I've read the docs but I can't understand which setting I need but I know it needs to go in here:

$(document).on("mobileinit", function() {
    //disable history?
});
like image 448
sidonaldson Avatar asked Dec 26 '22 08:12

sidonaldson


1 Answers

Add this code snippet after app initialize jQuery but before jQuery Mobile is initialized:

<script>
    $(document).on("mobileinit", function () {
        $.mobile.hashListeningEnabled = false;
        $.mobile.pushStateEnabled = false;
        $.mobile.changePage.defaults.changeHash = false;
    });
</script>

It should look like this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
    $(document).on("mobileinit", function () {
        $.mobile.hashListeningEnabled = false;
        $.mobile.pushStateEnabled = false;
    });
</script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.js"></script>

Remember this code MUST execute before jQuery Mobile is initialized or it will not work, but I guess you probably know this.

Example:

index.html:

<!DOCTYPE html>
<html>
    <head>
    <title>Page Title</title>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script>
        $(document).on("mobileinit", function () {
          $.mobile.hashListeningEnabled = false;
          $.mobile.pushStateEnabled = false;
          $.mobile.changePage.defaults.changeHash = false;
        });
    </script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.js"></script>
    <script>
    $(document).on('pagebeforeshow', '#index', function(){ 
        $(document).on('click', '#open-next-page', function(){ 
            $.mobile.changePage("#second", {transition: 'pop'});  
        });
    });
    </script>
</head>
<body>
<div data-role="page" id="index">
    <div data-role="header">
        <h1>Sample</h1>
    </div>
    <div data-role="content">
        <p></p>
        <p><a id="open-next-page" data-role="button">Open page 2</a></p>
    </div>
</div>
<div data-role="page" id="second">
    <div data-role="header">
        <a data-rel="back">Back</a>
        <h1>Page 2</h1>
    </div>
    <div data-role="content">
        This is page 2 content
    </div>
</div>  
</body>
</html>
like image 170
Gajotres Avatar answered Jun 11 '23 14:06

Gajotres