Cordova deviceready not firing in iOS until intera

2019-02-08 20:24发布

问题:

I had a really weird bug where deviceready event would not fire in an iOS device until the user interacted with the OS itself, this is, pressing the front button, show the notification center with drag down or go to device settings dragging up.

As soon as the user started dragging the iOS notification center, then deviceready fired.

Something as simple as this would just not work:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
  <meta http-equiv="Content-Security-Policy" content="default-src 'self' data:* gap:* tel:* 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'" />

  <title></title>

  <!-- cordova script (this will be a 404 during development) -->
  <script src="cordova.js"></script>
</head>

<body>
  <div id="log"></div>

  <script type="text/javascript">
    var log = document.getElementById("log");
    if(window.cordova){
        log.innerHTML = "with cordova";
        document.addEventListener("deviceready", function onDeviceReady(){
            log.innerHTML = "deviceready";
        }, false);
    }else{
        log.innerHTML = "with browser";
    }
  </script>
</body>
</html>

回答1:

The problem was really subtle. I spent about 4h debugging iOS why was cordova not firing until I saw i was just missing two //, right here:

  <meta http-equiv="Content-Security-Policy" content="default-src 'self' data:* gap://* tel:* 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'" />

that small gapin Content-Security-Policy had to have two //in front for it to work. This solved my bug, I still don't understand why .-.

Hope this helps!



回答2:

I had same issue on iOS. Finally any of these two workarounds worked for

  1. Add <meta http-equiv="Content-Security-Policy".......> to index.

  2. Downgrade platform to 4.0.0 (Cordova platform update iOS@4.0.0)

Performing the first option is preferable as downgrading to 4.0.0 is probably not preferable to you.