Navigator:getGamepads() 方法

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

* Some parts of this feature may have varying levels of support.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

Navigator.getGamepads() 方法返回一个包含 Gamepad 数组对象,每个对象代表与设备相连的一个游戏手柄。

如果游戏手柄在过程断开连接,则数组中的元素可能为 null,但剩余的游戏手柄的索引保持不变。

语法

js
getGamepads()

参数

无。

返回值

一个 Gamepad 对象的数组,最终可能为空。

异常

SecurityError DOMException

权限策略阻止了此特性的使用。

示例

js
window.addEventListener("gamepadconnected", (e) => {
  const gp = navigator.getGamepads()[e.gamepad.index];
  console.log(
    `游戏手柄在索引 ${gp.index} 处已连接:其 ID 为 ${gp.id},具有 ${gp.buttons.length} 个按键和 ${gp.axes.length} 个轴。`,
  );
});

规范

Specification
Gamepad
# dom-navigator-getgamepads

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
getGamepads
Secure context required
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.
Requires a vendor prefix or different name for use.
Has more compatibility info.

参见