Navigator: getGamepads() 方法

Baseline 广泛可用 *

此特性已得到良好确立,可跨多种设备和浏览器版本使用。自 2017 年 3 月起,所有浏览器均支持此特性。

* 此特性的某些部分可能存在不同级别的支持。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

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

如果游戏手柄在会话期间断开连接,数组中的元素可能是 null,以便剩余的游戏手柄可以保留相同的索引。

语法

js
getGamepads()

参数

无。

返回值

一个 Array 类型的 Gamepad 对象数组,可能为空。

异常

SecurityError DOMException

此功能的使用被 Permissions Policy 阻止了。

示例

js
window.addEventListener("gamepadconnected", (e) => {
  const gp = navigator.getGamepads()[e.gamepad.index];
  console.log(
    `Gamepad connected at index ${gp.index}: ${gp.id} with ${gp.buttons.length} buttons, ${gp.axes.length} axes.`,
  );
});

规范

规范
Gamepad
# dom-navigator-getgamepads

浏览器兼容性

另见