PhoneGap: Detect if running on desktop browser

后端 未结 30 2879
时光取名叫无心
时光取名叫无心 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:00

    The following works for me with the most recent PhoneGap / Cordova (2.1.0).

    How it works:

    • Very simple in concept
    • I inverted the logic of some of the above timeout solutions.
    • Register for the device_ready event (as recommended by the PhoneGap docs )
      • If the event has still NOT fired after a timeout, fallback to assuming a browser.
      • In contrast, the other solutions above rely on testing some PhoneGap feature or other, and watching their test break.

    Advantages:

    • Uses the PhoneGap-recommended device_ready event.
    • The mobile app has no delay. As soon as the device_ready event fires, we proceed.
    • No user-agent sniffing (I like testing my app as a mobile website so browser sniffing wasn't an option for me).
    • No reliance on undocumented (and therefore brittle) PhoneGap features/properties.
    • Keep your cordova.js in your codebase even when using a desktop or mobile browser. Thus, this answers the OP's question.
    • Wytze stated above: 'I wish cordova would set a parameter somewhere to say "We've tried finding a supported device and given up" but it seems like there is no such parameter.' So I provide one here.

    Disadvantages:

    • Timeouts are icky. But our mobile-app logic doesn't rely on a delay; rather, it is used as a fallback when we're in web-browser mode.

    ==

    Create a brand new blank PhoneGap project. In the provided sample index.js , replace the "app" variable at the bottom with this:

    var app = {
        // denotes whether we are within a mobile device (otherwise we're in a browser)
        iAmPhoneGap: false,
        // how long should we wait for PhoneGap to say the device is ready.
        howPatientAreWe: 10000,
        // id of the 'too_impatient' timeout
        timeoutID: null,
        // id of the 'impatience_remaining' interval reporting.
        impatienceProgressIntervalID: null,
    
        // Application Constructor
        initialize: function() {
            this.bindEvents();
        },
        // Bind Event Listeners
        //
        // Bind any events that are required on startup. Common events are:
        // `load`, `deviceready`, `offline`, and `online`.
        bindEvents: function() {
            document.addEventListener('deviceready', this.onDeviceReady, false);
            // after 10 seconds, if we still think we're NOT phonegap, give up.
            app.timeoutID = window.setTimeout(function(appReference) {
                if (!app.iAmPhoneGap) // jeepers, this has taken too long.
                    // manually trigger (fudge) the receivedEvent() method.   
                    appReference.receivedEvent('too_impatient');
            }, howPatientAreWe, this);
            // keep us updated on the console about how much longer to wait.
            app.impatienceProgressIntervalID = window.setInterval(function areWeThereYet() {
                    if (typeof areWeThereYet.howLongLeft == "undefined") { 
                        areWeThereYet.howLongLeft = app.howPatientAreWe; // create a static variable
                    } 
                    areWeThereYet.howLongLeft -= 1000; // not so much longer to wait.
    
                    console.log("areWeThereYet: Will give PhoneGap another " + areWeThereYet.howLongLeft + "ms");
                }, 1000);
        },
        // deviceready Event Handler
        //
        // The scope of `this` is the event. In order to call the `receivedEvent`
        // function, we must explicity call `app.receivedEvent(...);`
        onDeviceReady: function() {
            app.iAmPhoneGap = true; // We have a device.
            app.receivedEvent('deviceready');
    
            // clear the 'too_impatient' timeout .
            window.clearTimeout(app.timeoutID); 
        },
        // Update DOM on a Received Event
        receivedEvent: function(id) {
            // clear the "areWeThereYet" reporting.
            window.clearInterval(app.impatienceProgressIntervalID);
            console.log('Received Event: ' + id);
            myCustomJS(app.iAmPhoneGap); // run my application.
        }
    };
    
    app.initialize();
    
    function myCustomJS(trueIfIAmPhoneGap) {
        // put your custom javascript here.
        alert("I am "+ (trueIfIAmPhoneGap?"PhoneGap":"a Browser"));
    }
    

提交回复
热议问题