PhoneGap: Detect if running on desktop browser

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

    The essence of the problem is that so long as cordova.device is undefined, your code can't be sure if that's because cordova has established that your device is not supported, or if it's because cordova is still preparing itself and deviceready will fire later (or third option: cordova didn't load properly).

    The only solution is to define a waiting period, and to decide that after this period your code must assume the device is not supported. 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.

    Once this is established, you may want to do something specific precisely in those situations where there is no supported device. Like hiding links to the device's app market, in my case.

    I've pieced together this function which should cover pretty much every situation. It lets you define a deviceready handler, a device-never-ready handler, and a waiting time.

    //Deals with the possibility that the code will run on a non-phoneGap supported
    //device such as desktop browsers. Gives several options including waiting a while
    //for cordova to load after all.
    //In:
    //onceReady (function) - performed as soon as deviceready fires
    //patience 
    //  (int) - time to wait before establishing that cordova will never load
    //  (boolean false) - don't wait: assume that deviceready will never fire
    //neverReady 
    //  (function) - performed once it's established deviceready will never fire
    //  (boolean true) - if deviceready will never fire, run onceReady anyhow
    //  (boolean false or undefined) - if deviceready will never fire, do nothing
    function deviceReadyOrNot(onceReady,patience,neverReady){
    
        if (!window.cordova){
                console.log('Cordova was not loaded when it should have been')
                if (typeof neverReady == "function"){neverReady();}
            //If phoneGap script loaded...
            } else {
                //And device is ready by now...
                if  (cordova.device){
                    callback();
                //...or it's loaded but device is not ready
                } else {
                    //...we might run the callback after
                    if (typeof patience == "number"){
                        //Run the callback as soon as deviceready fires
                        document.addEventListener('deviceready.patience',function(){
                            if (typeof onceReady == "function"){onceReady();}
                        })
                        //Set a timeout to disable the listener
                        window.setTimeout(function(){
                            //If patience has run out, unbind the handler
                            $(document).unbind('deviceready.patience');
                            //If desired, manually run the callback right now
                            if (typeof neverReady == 'function'){neverReady();}
                        },patience);
                    //...or we might just do nothing
                    } else {
                        //Don't bind a deviceready handler: assume it will never happen
                        if (typeof neverReady == 'function'){neverReady();} 
                        else if (neverReady === true){onceReady();} 
                        else {
                           //Do nothing
                        }
                    }
                }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 15:54

    I was trying with the window objects but it didn't worked as I was opening the remote url in the InAppBrowser. Couldn't get it done. So the best and easiest way to achieve it was to append a string to the url which you need to open from the phonegap app. Then check if the document location has string appended to it.

    Below is the simple code for it

    var ref = window.open('http://yourdomain.org#phonegap', '_blank', 'location=yes');
    

    You will see a string is added to the url "#phonegap".So in the domain url add the following script

    if(window.location.indexOf("#phonegap") > -1){
         alert("Url Loaded in the phonegap App");
    }
    
    0 讨论(0)
  • 2020-11-29 15:55

    GeorgeW's solution is OK, but even on real device, PhoneGap.available is only true after PhoneGap's things has been loaded, e.g. onDeviceReady in document.addEventListener('deviceready', onDeviceReady, false) has been called.

    Before that time, if you want to know, you can do like this:

    runningInPcBrowser =
        navigator.userAgent.indexOf('Chrome')  >= 0 ||
        navigator.userAgent.indexOf('Firefox') >= 0
    

    This solution assumes that most developers develop using Chrome or Firefox.

    0 讨论(0)
  • 2020-11-29 15:58

    None of which work, unless you remove the PhoneGap Javascript file from the desktop version of the app, which defeats my goal of having one codebase.

    Another option would be to use merges folder, see screenshot below.

    You can add platform-specific files / override default ones.

    (it should do the trick in some scenarios)

    enter image description here


    In other words: Rather than detecting the browser, you just don't include certain files for desktop build / attach certain files for iOS only.

    0 讨论(0)
  • 2020-11-29 15:59

    I wrote a post about it a few days ago. This is the best solution you can find (until PhoneGap will release something, maybe or maybe not), it's short, simple and perfect (I've checked it in every possible way and platform).

    This function will do the job for 98% of the cases.

    /**
     * Determine whether the file loaded from PhoneGap or not
     */
    function isPhoneGap() {
        return (window.cordova || window.PhoneGap || window.phonegap) 
        && /^file:\/{3}[^\/]/i.test(window.location.href) 
        && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
    }
    
    if ( isPhoneGap() ) {
        alert("Running on PhoneGap!");
    } else {
        alert("Not running on PhoneGap!");
    }
    

    To complete the other 2% of the cases, follow these steps (it involves a slight change on native code):

    Create a file called __phonegap_index.html, with the source:

    <!-- __phonegap_index.html -->
    <script type="text/javascript">
        function isPhoneGap() {
            //the function's content is as described above
        }
    
        //ensure the 98% that this file is called from PhoneGap.
        //in case somebody accessed this file directly from the browser.
        if ( isPhoneGap() )
            localStorage.setItem("isPhoneGap","1");
    
        //and redirect to the main site file.
        window.location = "index.html";
    </script>
    

    Now, on native simply change the start page from index.html to __phonegap_index.html on all your PhoneGap platforms. Let's say my project name is example, the files you need to change are (as for PhoneGap version 2.2.0):

    • iOS - CordovaLibApp/AppDelegate.m
    • Android - src/org/apache/cordova/example/cordovaExample.java
    • Windows 8 - example/package.appxmanifest
    • BlackBerry - www/config.xml
    • WebOS - framework/appinfo.json
    • Bada - src/WebForm.cpp (line 56)
    • Window Phone 7 - No idea where (somebody still developing on that platform?!)

    Finally, you can use it anywhere on your site, if it's running on PhoneGap or not:

    if ( localStorage.getItem("isPhoneGap") ) {
        alert("Running on PhoneGap!");
    } else {
        alert("Not running on PhoneGap!");
    }
    

    Hope it helps. :-)

    0 讨论(0)
  • 2020-11-29 16:00

    I use this code:

    if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
      document.addEventListener("deviceready", onDeviceReady, false);
    } else {
      onDeviceReady(); //this is the browser
    }
    

    UPDATE

    There are many other ways to detect if phonegap is running on a browser or not, here is another great option:

    var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
    if ( app ) {
        // PhoneGap application
    } else {
        // Web page
    }  
    

    as seen here: Detect between a mobile browser or a PhoneGap application

    0 讨论(0)
提交回复
热议问题