gpt4 book ai didi

capacitor - 如何确定当前平台是 Capacitor 中的 native 应用程序还是 Web?

转载 作者:行者123 更新时间:2023-12-04 06:44:18 24 4
gpt4 key购买 nike

在 Cordova ,您可以立即访问 process.env.CORDOVA_PLATFORM电容器中有类似的东西吗?

我希望在启动时有条件地加载一些函数,并且不想阻止渲染等待异步 Device.getInfo回来。

例如,我想立即确定是否导入进行 native 键盘修改的脚本,但如果我们在网络上运行,我不想导入此脚本

try {
const { Keyboard } = Plugins
Keyboard.setAccessoryBarVisible({ isVisible: true })
} catch (error) {
// Keyboard isn't available on web so we need to swallow the error
}

我正在使用 vue-cli

最佳答案

到目前为止的答案都是正确的,如果您查看 Capacitors 源代码,有几种可用的方法可以使用(但目前没有记录):

  • Capacitor.getPlatform();//-> 'web', 'ios' 或 'android'
  • Capacitor.platform//-> 'web', 'ios' 或 'android'
  • Capacitor.isNative//-> 真或假

  • 请注意,该方法 Capacitor.isPluginAvailable('PluginName');仅在插件可用与否(显然)时返回,但在这里很重要,它不会告诉您,检查可用性后要执行的方法是否适用于您的平台。

    Capacitor Plugins 的文档尚未完成(尚未完成)。

    示例(代码),用于插件 StatusBar :
    // Native StatusBar Plugin available
    if (Capacitor.isPluginAvailable('StatusBar')) {

    // Tint statusbar color
    StatusBar.setBackgroundColor({
    color: '#FF0000'
    });

    }

    这将导致 iOS 上的错误,因为此方法在那里不可用,在 Android 上它到目前为止工作正常。

    这意味着,您需要自己实现对插件和平台组合的检查(目前), future 可能会由 Ionic/Capacitor 本身改进。

    就像是:
    // Native StatusBar available
    if (Capacitor.getPlatform() === 'android' && Capacitor.isPluginAvailable('StatusBar')) {

    // Tint statusbar color
    StatusBar.setBackgroundColor({
    color: this.config.module.GYMY_MODAL_STATUSBAR_HEX_STRING
    });

    }

    还有一件事,您无法检查此插件中是否存在该方法(对于上面的代码 setBackgroundColor 的fe),因为它可用,但在不支持的平台上引发错误( Error: not implemented )它。

    希望我能帮助你们中的一些人。

    干杯
    未知0wn0x

    关于capacitor - 如何确定当前平台是 Capacitor 中的 native 应用程序还是 Web?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745387/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com