以下内容适用于最新的PhoneGap / Cordova(2.1.0)。
这个怎么运作:
- 概念很简单
- 我颠倒了上述某些超时解决方案的逻辑。
- 注册device_ready事件(根据PhoneGap docs的建议)
- 如果事件在超时后仍未触发,则退回至假定浏览器。
- 相反,以上其他解决方案则依赖于测试某些PhoneGap功能或其他功能,并观察其测试中断。
优点:
- 使用推荐的PhoneGap device_ready事件。
- 移动应用程序没有延迟。一旦device_ready事件触发,我们就继续。
- 没有用户代理嗅探(我喜欢将我的应用作为移动网站进行测试,因此浏览器嗅探对我而言不是一种选择)。
- 不依赖未记录的(因此易碎的)PhoneGap功能/属性。
- 即使使用台式机或移动浏览器,也应将cordova.js保留在代码库中。因此,这回答了OP的问题。
- Wytze在上面说过:“我希望Cordova在某个地方设置一个参数,说“我们试图找到一种受支持的设备并放弃了”,但似乎没有这样的参数。所以我在这里提供一个。
缺点:
- 超时很糟糕。但是我们的移动应用逻辑并不依赖于延迟。相反,当我们处于网络浏览器模式时,它用作备用。
==
创建一个全新的空白PhoneGap项目。在提供的样本index.js中,将底部的“ app”变量替换为此:
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"));
}