Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
在Google Chrome(版本100)上运行时,您遇到的错误不会出现。
看起来一些浏览器不支持
navigator.getBattery()
。请参阅) ,❌=不支持。
如果您注意到不支持所使用的浏览器,则应升级或切换它,运行代码,然后可以使用。
另外,代码中的另一个问题是,当不存在
电池
时,您正在尝试获取电池
。这可能会出现错误。看来您想使用返回的
BatteryManager
对象,在这种情况下,a
。因此,要修复它,只需使用下面的代码即可。现在,这是从已经定义的
a
变量中获取Level
属性。将代码更改为此,它应该正确工作。The error that you are getting is not coming up when running on Google Chrome (version 100).
It looks like a few browsers don't support
navigator.getBattery()
. See the browser compatibility on MDN, or see the table below.Key: ✅ = Supported, ❌ = Not supported.
If you notice that the browser that you are using isn't supported, you should upgrade or switch it, run the code, and it should work then.
Also, another problem in your code is that you are trying to get
battery.level
, whenbattery
doesn't exist. This will likely throw an error.It looks like you want to use the returned
BatteryManager
object, in this case,a
. So, to fix it, simply use the code below.This is now getting the
level
property from the already-defineda
variable. When you change your code to this, it should work correctly.您遇到了使用变量
a
的问题,但正在引用电池
。查看我的编辑和工作演示:You had an issue where you were using a variable
a
but were referencingbattery
. See my edits and working demo:此特定错误消息的一个常见原因是,如果页面未在安全上下文(HTTPS)中运行,则许多浏览器会阻止电池API。
检查兼容性图表的“安全上下文必需的上下文”行: https://developer.mozilla.org/en-us/docs/web/api/navigator/getBattery#browser_compatibility
由于这是此错误消息的最佳Google搜索结果,即使值得一提的是,即使这个问题被标记为解决。
One common cause of this specific error message is that many browsers block the battery API if the page is not running in a secure context (HTTPS).
Check the "Secure Context Required" row of the compatibility chart: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getBattery#browser_compatibility
Since this is now the top google search result for this error message, it's worth noting, even though this question is marked as solved.