Navigator: phương thức 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.

Phương thức Navigator.getGamepads() trả về một mảng gồm Các đối tượng Gamepad, một đối tượng cho mỗi gamepad được kết nối với thiết bị.

Các phần tử trong mảng có thể là null nếu gamepad ngắt kết nối trong khi phiên, để các gamepad còn lại giữ nguyên chỉ mục.

Cú pháp

js
getGamepads()

Thông số

Không có.

Giá trị trả về

Array của đối tượng Gamepad, cuối cùng sẽ trống.

Ngoại lệ

SecurityError DOMException

Việc sử dụng tính năng này đã bị Permissions Policy chặn.

Ví dụ

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.`,
  );
});

Thông số kỹ thuật

Specification
Gamepad
# dom-navigator-getgamepads

Khả năng tương thích của trình duyệt

Xem thêm