【问题标题】:Check if device supports ScreenOrientation.lock() - Uncaught Error screen.orientation.lock() is not available on this device检查设备是否支持 ScreenOrientation.lock() - 未捕获的错误 screen.orientation.lock() 在此设备上不可用
【发布时间】:2020-08-28 00:27:50
【问题描述】:

我正在关注ScreenOrientation.lock() 的文档,但我无法让它按我的意愿工作。

https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock

在 Chrome 桌面上调用 window.screen.orientation.lock("portrait"); 时,我收到错误 screen.orientation.lock() is not available on this device. 作为未捕获错误。有没有办法检查设备是否支持锁定?

我已经将"orientation":"portrait" 放入manifest.json,但这只是默认方向,不是锁定。

https://www.w3.org/TR/appmanifest/#orientation-member

旁注:

我在理解如何调用该方法时遇到了一些麻烦。如果有人发现此线程,则示例错误:

ScreenOrientation.prototype.lock("portrait");

window.ScreenOrientation.prototype.lock("portrait");

导致此异常:

未处理的拒绝(TypeError):无法执行“锁定” 'ScreenOrientation':非法调用

(ScreenOrientation as any).lock("portrait");

导致此异常:

TypeError: ScreenOrientation.lock 不是函数

【问题讨论】:

  • 一个后备方法是捕获异常。没有严格回答“检测是否”的前手。

标签: javascript css typescript


【解决方案1】:

window.screen.orientation.lock() 返回一个Promise。 Promise 将调用您提供给链式 then() 方法的函数之一,具体取决于 Promise 是已解决(成功)还是被拒绝(失败)。

您可以像这样致电window.screen.orientation.lock()

window.screen.orientation
    .lock("portrait")
    .then(
        success => console.log(success),
        failure => console.log(failure)
    )

您可能希望在 resolvereject 方法中添加一些更有用的东西,但这至少可以捕获拒绝并防止抛出 Unhandled Rejection 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多