'How to trigger cordova's backbutton event programatically

I'm developing a phonegap app based on jQuery mobile. I'm trying to put a button in my app, behaving like back button on android devices. I don't want just a history.back(), but I want the exactly same behavior, means going back when no handler is attached, and performing the handler when one is attached to the event backbutton.

In other words, I want to simulate hardware back button, in software (exactly same behavior)

I've tried these codes, with no success:

$("#backbtn").click(function(){
    var backButtonEvent = document.createEvent('Events');
    backButtonEvent.initEvent('backbutton', false, false);
    document.dispatchEvent(backButtonEvent);
});

What can I do?



Solution 1:[1]

import javascriptinterface package in mainActivity class

import android.webkit.JavascriptInterface;

add JavaScript interface in onCreate method in the MainActivity Class

super.appView.addJavascriptInterface(new JSInterface(), "sampleproj");

Then define the javascript Interface

public class JSInterface{
       @JavascriptInterface
       public void dispachBackKey() {
            dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
            dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
       }
}

Now call the native method in javascript

window.sampleproj.dispachBackKey();

Solution 2:[2]

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

function onDeviceReady(){
    var backButtonElement = document.getElementById("backbtn");
    backButtonElement .addEventListener("click", buttonCallBack, false);
}

function buttonCallBack(){
    document.addEventListener("backbutton", onBackButton, false);
}
function onBackButton(){
   // write your stuff
}

Try the above code it will work

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Naresh Kumar