PhoneGap: Detect if running on desktop browser

后端 未结 30 2824
时光取名叫无心
时光取名叫无心 2020-11-29 15:47

I\'m developing a web application that uses PhoneGap:Build for a mobile version and want to have a single codebase for the \'desktop\' and mobile versions. I want to be able

30条回答
  •  春和景丽
    2020-11-29 16:08

    Like the original poster, I'm using the phonegap build service. After two days and nearly 50 test builds, I've come up with an elegant solution that works great for me.

    I couldn't use UA sniffing because I wanted to test and run in mobile browsers. I had originally settled on cobberboy's quite functional technique. This didn't work for me because the "howPatientAreWe: 10000" delay/timeout was too much of a nuisance for in-browser development. And setting it any lower would occasionally fail the test in app/device mode. There had to be another way...

    The phonegap build service requires the phonegap.js file be omitted from your code repository before submitting your app's files to the service. Therefore I'm able to test for its existence to determine if running in a browser vs. app.

    One other caveat, I'm also using jQueryMobile, so both jQM and phonegap had to initialize before I could begin any custom scripting. The following code is placed at the beginning of my custom index.js file for the app (after jQuery, before jQM). Also the phonegap build docs say to place somewhere in the HTML. I leave it out completely and load it using $.getScript() to facility testing its existence.

    isPhoneGap = false;
    isPhoneGapReady = false;
    isjQMReady = false;
    
    $.getScript("phonegap.js")
    .done(function () {
        isPhoneGap = true;
        document.addEventListener("deviceready", function () {
            console.log("phonegap ready - device/app mode");
            isPhoneGapReady = true;
            Application.checkReadyState();
        }, false);
    })
    .fail(function () {
        console.log("phonegap load failed - browser only");
        isPhoneGapReady = true;
        Application.checkReadyState();
    });
    
    $(document).bind("mobileinit", function () {
        Application.mobileInit();
        $(document).one("pageinit", "#Your_First_jQM_Page", function () {
            isjQMReady = true;
            Application.checkReadyState();
        });
    });
    
    Application = {
        checkReadyState: function () {
            if (isjQMReady && isPhoneGapReady) {
                Application.ready();
            }
        },
        mobileInit: function () {
            // jQM initialization settings go here
            // i.e. $.mobile.defaultPageTransition = 'slide';
        },
        ready: function () {
            // Both phonegap (if available) and jQM are fired up and ready
            // let the custom scripting begin!
        }
    }
    

提交回复
热议问题