Override Android Backbutton behavior only works on the first page with PhoneGap

让人想犯罪 __ 提交于 2019-11-26 16:35:56

I gone through the new Phonegap source code and did following changes to make the backbutton work.

Html test code

<script type="text/javascript">
    $("#home").click(function(){
        $.mobile.changePage("home.html");
    });

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

    function onDeviceReady() {
        console.log("PhoneGap Ready!");
    }

    function handleBackButton() {
        console.log("Back Button Pressed!");
        navigator.app.exitApp();
    }
</script>

Put the following code in the else block of document.addEventListener in cordova-1.5.0.js after line-no 507

if (e === 'backbutton') {
    var exec = require('cordova/exec')
    exec(null, null, "App", "overrideBackbutton", [true]);
}

Put following code in fireDocumentEvent method of cordova definition in cordova-1.5.0.js after line-no 592

if(type == "backbutton"){
    var e = document.createEvent('Events');
    e.initEvent(type);
    if (data) {
        for (var i in data) {
            e[i] = data[i];
        }
    }
    document.dispatchEvent(e);
    return;
}

I have put the whole cordova-1.5.0.js in this gist with updated code https://gist.github.com/2020325

Though it is working for me but it still may need some changes to work in all the possible scenarios.

Edit

Put following code in fireDocumentEvent method of cordova definition in cordova-1.5.0.js after line-no 592

if(type == "backbutton" || type == "menubutton" || type == "searchbutton"){
        var e = document.createEvent('Events');
        e.initEvent(type);
        if (data) {
            for (var i in data) {
                e[i] = data[i];
            }
        }
        document.dispatchEvent(e);
        return;
    }
Guillaume Gendre

Bryce Curtis is suggesting on that page to just change the line :

channel.onNativeReady.subscribe(_self.boot);

to :

channel.onNativeReady.subscribeOnce(_self.boot);

at the end of the file.

That seems to do the trick for me and fixed the backbutton AND the menubutton and searchbutton !

@dhaval : I have done the following changes in the cordova-1.5.0.js in Android.

The pages where I have not handled back button is working fine, But the place where I am handling the Back button does not work.

Its not even able to pick the function

function handleBackButton() {

  console.log("Back Button Pressed!");
    navigator.app.exitApp();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!