如何动态更改索引中包含的脚本.html - 角度 2.



我正在尝试在Cordova应用程序中使用Angular网站。Cordova应用程序加载Angular远程网址。Angular 索引.html包含 cordova.js 文件。然而,科尔多瓦.js是特定于平台的。Android和iOS都有自己的cordova.js文件版本。如何在运行时检测浏览器代理/平台并在索引.html中加载特定于平台的cordova.js文件?

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

您可以使用 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;检查操作系统

最新更新