Shashidhar Yamsani
Shashidhar Yamsani

Reputation: 573

How to dynamically change included scripts in index.html - Angular 2?

I'm trying to use an Angular website in Cordova app. The Cordova app loads the Angular remote url. The Angular index.html has the cordova.js file included. However cordova.js is specific to platform. Android and iOS has their own version of cordova.js file. How to detect the browser agent/platform at runtime and load platform specific cordova.js file in index.html?

Upvotes: 1

Views: 1794

Answers (2)

Shashidhar Yamsani
Shashidhar Yamsani

Reputation: 573

Answering my own question. I'm checking the device type in the onload event and appending the platform specific cordova.js script line to the index.html.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My Sample App</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">

  <script type="text/javascript">
    function loadCordova() {

      //check mobile device type
      var isiOS = /(ipod|iphone|ipad)/i.test(navigator.userAgent);
      var isAndroid = /(android)/i.test(navigator.userAgent);
      console.log('platform', navigator.platform);
      var my_awesome_script = document.createElement('script');

      //set the source of script tag based on the mobile device type.
      if(isiOS) {
        my_awesome_script.setAttribute('src','ios/cordova.js');
      } else if(isAndroid) {
        my_awesome_script.setAttribute('src','android/cordova.js');
      }

      //append the script tag to document head.
      document.head.appendChild(my_awesome_script);
      console.log('End of loadCordova.')
    }
  </script>

</head>
<body onload="loadCordova()">
  <app-root></app-root>
</body>
</html>

Upvotes: 1

Jaime Cuellar
Jaime Cuellar

Reputation: 474

You can use cordova device plugin to check on what device you are running the app. https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-device/

Inside your app.js (if im not wrong) you have to add

document.addEventListener("deviceready", onDeviceReady, false); 
function onDeviceReady() {
console.log(device.cordova);
}

and you can check for OS with var string = device.platform;

Upvotes: 0

Related Questions