如何在index.html中动态更改包含的脚本 - Angular 2?

时间:2018-04-17 16:29:00

标签: angular cordova

我试图在Cordova app中使用Angular网站。 Cordova应用程序加载Angular远程URL。 Angular index.html包含cordova.js文件。但是cordova.js特定于平台。 Android和iOS有自己版本的cordova.js文件。如何在运行时检测浏览器代理/平台并在index.html中加载特定于平台的cordova.js文件?

2 个答案:

答案 0 :(得分:1)

回答我自己的问题。我正在检查onload事件中的设备类型,并将特定于平台的cordova.js脚本行附加到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>

答案 1 :(得分:0)

您可以使用cordova设备插件检查您运行该应用的设备。 https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-device/

app.js内(如果我没错)你必须添加

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

您可以使用var string = device.platform;

检查操作系统