Jorge Ramírez Jorge Ramírez - 7 months ago 25
Javascript Question

Execute js function when accessing a page from browser's back button

I'm developing a website using jquery mobile 1.2.0 and jquery 1.7.2, I'm facing an issue trying to execute a js function when the page is loaded.

The normal scenario is that the user loads the page using a link (anchor) so I'm handling the jquery mobile event "pageinit", that works ok, but I need to execute the same code/function when the user access the page using the browser's back button, in that case the "pageinit" event is never fired.

The javascript function modifies the UI so it is needed the UI is loaded before the function gets called.

I'm testing it on Safari 9.1 (iOS 9.3).

My page is very similar to this:

<section id="someid" data-role="page" data-theme="a">
<!-- Page content -->
</section>

<script type="text/javascript">
function myFunction() {
//some code to modify de UI on page loaded
}

$("#someid").on("pageinit", function (e) {
var page = $(this);

myFunction();
});
</script>


UPDATE 1:

I've tested all the jquery mobile's events listed here without any luck.

Answer

Finally I found this SO question that lets me fix the issue, basically it's to use the window event "popstate", here is the exact code I used:

<section id="someid" data-role="page" data-theme="a">
<!-- Page content -->
</section>

<script type="text/javascript">
function myFunction() {
//some code to modify de UI on page loaded
}

$("#someid").on("pageinit", function (e) {
    var page = $(this);

    myFunction();
});

var myCustomEvent = (navigator.userAgent.match('iPhone') != null) ? 'popstate' : 'pageshow';

$(window).on(myCustomEvent, function(e) {
    myFunction();
}
</script>

Note1: The event "pageshow" is perfectly evaluated by most browsers different than Safari Mobile, so it's checking it for those cases.

Note2: I tested this code on Safari Mobile 9.1 (iOS 9.3).

Comments