Detect between a mobile browser or a PhoneGap application

后端 未结 16 1974
小蘑菇
小蘑菇 2020-11-28 03:03

Is it possible to detect if the user is accessing through the browser or application using JavaScript?

I\'m developing a hybrid application to several mobile OS thr

16条回答
  •  没有蜡笔的小新
    2020-11-28 03:21

    Solution: Patch index.html in Cordova and add cordova-platform="android" to tag, so that cordova-platform attribute will be only present in Cordova build and missing from original index.html used for web outside of Cordova.

    Pros: Not rely on user agent, url schema or cordova API. Does not need to wait for deviceready event. Can be extended in various ways, for example cordova-platform="browser" may be included or not, in order to distinguish between web app outside of Cordova with Cordova's browser platform build.

    Merge with config.xml

        
            
        
    

    Add file scripts/patch-android-index.js

    module.exports = function(ctx) {
        var fs = ctx.requireCordovaModule('fs');
        var path = ctx.requireCordovaModule('path');
    
        var platformRoot = path.join(ctx.opts.projectRoot, 'platforms/android');
        var indexPath = platformRoot + '/app/src/main/assets/www/index.html';
    
        var indexSource = fs.readFileSync(indexPath, 'utf-8');
    
        indexSource = indexSource.replace('

    Notes: For other than android, the paths platforms/android and /app/src/main/assets/www/index.html should be adjusted.

    App can check for cordova-platform with

    if (! document.documentElement.getAttribute('cordova-platform')) {
      // Not in Cordova
    }
    

    or

    if (document.documentElement.getAttribute('cordova-platform') === 'android') {
      // Cordova, Android
    }
    

提交回复
热议问题