How to make back button previous state?

I look at the forum and I found this

document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() 
    {
       document.addEventListener("backbutton", onBackKeyDown, false);
    }

    function onBackKeyDown () 
    {
    	console.log('Back button event');
        var currentPage = mainView.router.currentRoute.name;

    	if (currentPage == 'page-home')
        {
            navigator.app.exitApp();
        } 
        else 
        {
    	    mainView.router.back();
        }
    } 

But still nothing, the backbutton leave the app…

On to achive this please ?

function onBackKeyDown (e) 
    {
    	console.log('Back button event');
        var currentPage = mainView.router.currentRoute.name;

    	if (currentPage == 'page-home')
        {
            navigator.app.exitApp();
        } 
        else 
        {
    	    mainView.router.back();
            e.preventDefault();
            return false;
        }
    } 

I want to close popUp if it’s open, and then go back, and if is Home page exit.
I try this, but not work, always exits the app.

function onBackKeyDown(e) {
            var currentPage = mainView.router.currentRoute.name;
            if ($$('.modal-in').length > 0) {
                app.popup.close();
        	} else if (currentPage == 'home') {
                navigator.app.exitApp();
            } else {
        		mainView.router.back();
                e.preventDefault();
                return false;
        	}
}

I made some changes, but always the same, exits app.

This code works, for close the popUp and go back.

function onBackKeyDown() {
	if ($$('.modal-in').length > 0) {
        app.popup.close();
		return false;
	} else {
		mainView.router.back();
	}
	return true;
};

When I add the exit app part, stop working.

Hi,
Thanks for the reply.
The back button was disabled but stil not getting back to the previous route

What’s the mainView ?

What is your code? mainView in v4 is app.views.main