Cordova: judge whether the page is opened in a device app

I'm using cordova, and serving the site (remote, not local file in the cordova app project) to either ordinary browser and the specific app install on my phone.

Now comes the question, if the page is opened inside the app, the cordova script should be introduced, while if it is opened under an ordinary browser, that shouldn't happen.

So I wonder if there is a way to tell whether the page is open inside the app?

if (isApp()) {
    document.addEventListener('deviceready', () => {
        bootstrap();
    }
} else {
    bootstrap();
}

I spy the UserAgent in both case, it seemed there isn't any significant information there.

Or if I can add some UserAgent information in the cordova project?


您可以测试window.cordova以确定您的应用程序是否在Cordova环境中运行(即cordova.js包含在页面中)


Add the following line to /config.xml .

See: http://cordova.apache.org/docs/en/dev/config_ref/index.html#Android%20Configuration

<preference name="AppendUserAgent" value="Cordova" />

Then, we can use the follwing condition in the very early time to judge:

function isApp() {
    return /Cordova/.test(windows.navigator.userAgent);
}

We can event decide whether to introduce the cordova.js:

let cordovaReady = null;

if (/Cordova/.test(window.navigator.userAgent)) {
  cordovaReady = new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/cordova/cordova.js';
    script.onload = () => {
      document.addEventListener('deviceready', () => {
        resolve();
      }, false);
    };
    document.body.appendChild(script);
  });
} else {
    cordovaReady = Promise.reject();
}

// We got cordovaReady as a Promise that tells both `inApp()` and `deviceready`.
cordovaReady.then(() => { // done
    // windows.cordova is available
}, () => { // fail
    // windows.cordova is undefined
    console.log('The page is not open under Cordova App.');
}).then(() => { // always
    // launch your app
    bootstrap();
});
链接地址: http://www.djcxy.com/p/79774.html

上一篇: 使用Cordova webview

下一篇: Cordova:判断该页面是否在设备应用程序中打开