Notice: The Monaca & Onsen UI Community Forum is shutting down.

For Onsen UI bug reports, feature requests and questions, please use the Onsen UI GitHub issues page. For help with Monaca, please contact Monaca Support Team.

Thank you to all our community for your contributions to the forum. We look forward to hearing from you in the new communication channels.

Perform function on closing a page using ons-navigator



  • I have a small app that uses ons-navigator to load 3 or 4 different pages. One 1 page load, I run a function to ensure the user is online (has an internet connection) using an event listener. When that page closes, I would like to remove that event listener. How do I run a function on both the user hitting the BACK button or swiping back (this is for iOS)?



  • Hi,

    I have done this in my project before, to avoid user back accidentally.

    "ons-back-button: is a component that shows the button and also the action “popPage()”, so we cannot use it. Instead of “<div class=“left”><ons-back-button>Page 1</ons-back-button></div>”, we use the following to draw the back-button.

    <div class="back-button" style="display: inline-block;" onclick="showConfirm()">
        <span class="back-button__icon">
            <!--?xml version="1.0" encoding="UTF-8"?-->
            <svg width="13px" height="21px" viewBox="0 0 13 21" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <title>ios-back-button-icon</title>
                <g id="toolbar-back-button" stroke="none" stroke-width="1" fill-rule="evenodd">
                    <g id="ios" transform="translate(-34.000000, -30.000000)">
                        <polygon id="ios-back-button-icon" points="34 40.5 44.5 30 46.5 32 38 40.5 46.5 49 44.5 51"></polygon>
                   </g>
               </g>
           </svg>
        </span>
        <span class="back-button__label" style="">Page 1</span>
    </div>
    

    We have to write the back-button function by ourselves, we call it “showConfirm()”. Ask your confirmation before popPage().

    var showConfirm = function() {
        ons.notification.confirm({
            message: 'Are you sure to exit?',
            buttonLabels: ['Yes', 'No'],
            primaryButtonIndex: 1,
            callback: function(i) {
                if (i === 0) {
                     document.querySelector('#myNavigator').popPage()
                } else {
                    ons.notification.alert('You have cancelled back to page 1');
                }
            }
        })
    };
    

    So when you press the back button, it will show a dialog to have your confirmation, if you press ‘yes’, then it will go back to page 1.

    Best Regards
    Gobi