# Troubleshooting

> Fix common @gamepadly/sdk problems. The controller is not detected, a keyboard game ignores it, buttons are swapped, the WebHID picker does not open or fails in an iframe, haptics return 'none', adaptive triggers do not resist, or tests fail in Node.

Source: https://gamepadly.com/sdk/troubleshooting

Find the symptom below. Each answer says what causes it and how to fix it. Unless an answer says otherwise, the
browser behavior described here was checked in desktop Chromium. Items marked _not tested_ come from browser and
vendor documentation, not from our own runs.

## First, see what the SDK sees

Log what the SDK reports about the active controller. Every capability it cannot use carries a reason:

```ts
import { createGamepadly } from '@gamepadly/sdk';

const hub = createGamepadly();
hub.onCapabilitiesChange(() => {
  const caps = hub.active.getCapabilities();
  console.log(caps.tier, caps.identity.displayName, hub.active.input.getState().mapping);
  for (const [id, status] of Object.entries(caps.matrix)) {
    if (status.reason) console.log(id, status.availability, status.reason);
  }
});
```

`tier` is `'keyboard_mouse'` until a controller is detected. To check the controller and browser without your game
involved, open the [online controller tester](https://gamepadly.com/). If the tester does not see the controller,
your game will not either.

## The controller is not detected

- **No button has been pressed yet.** Browsers report a controller only after the player presses a button on it
  while the page is open, so the page cannot learn which controllers you own. Moving a stick or plugging the
  controller in is not always enough. Show a "Press any button" hint until `tier` changes.
- **The tab is in the background.** Browsers send controller input only to the visible tab. The game resumes when
  its tab is shown again.
- **The cable only charges.** A charge-only USB cable powers the controller but carries no data. Try another cable,
  or pair the controller over Bluetooth.
- **Another program owns the controller** (_not tested_). Remapping tools such as DS4Windows or reWASD can hide the
  controller from other programs, or show it to them as a virtual Xbox controller. If the browser reports an Xbox
  360 controller while you hold a DualSense, a remapper is the likely cause. Close it and reconnect the controller.

## A keyboard game ignores the controller

This section applies to games that use the [bridge](https://gamepadly.com/sdk/start/add-controller).

- **The game listens on an element.** By default the bridge dispatches its key events on `document`, and from
  there they bubble up to `window`. Events never travel down to elements, so a game that listens on its canvas never
  sees them. Pass that element as `keyTarget`. See
  [how your game reads the keyboard](https://gamepadly.com/sdk/start/add-controller#2-find-how-your-game-reads-the-keyboard). Before
  0.7.0 the default target was `window`, which `document` listeners do not hear.
- **The profile presses other keys.** Compare the keys the game reads (`event.code`, `event.key` or `keyCode`) with
  the keys in your profile. The built-in `'platformer'` profile presses the arrow keys, Space and Z. A WASD game
  needs its own profile.
- **The game checks `event.isTrusted`.** Events created by a script, the bridge's included, always have
  `isTrusted: false`, and some games skip such events. Remove the check, or read the controller with an
  [action map](https://gamepadly.com/sdk/guides/input-and-actions) instead of the bridge.

The bridge stops pressing keys, and releases any it holds, when no controller is connected. The keyboard always
keeps working.

## Buttons are wrong or swapped

- **The browser reports a non-standard layout.** When `getState().mapping` is `'nonstandard'`, the browser did not
  map the controller's buttons to the standard positions, so they can be misnamed. This happens more often in
  Firefox, Safari and with some third-party controllers. Connect DualSense and Switch Pro controllers over WebHID,
  which reads them directly, or supply a layout with `gamepadMappings`. See
  [Non-standard layouts](https://gamepadly.com/sdk/guides/buttons-and-layouts#non-standard-layouts).
- **A and B look swapped on Nintendo controllers.** This is by design. `south` is the bottom face button, which is
  A on Xbox and B on Nintendo, so the same code works for both. Show the player's own label with
  `getButtonLabel('south', caps.identity.brand)`.

## The character drifts, or a press is missed

- **The stick is read raw.** `getState()` returns sticks with no deadzone, so a worn stick that rests at 0.03 moves
  the character. Read movement through an action map axis, which has a 0.08 deadzone by default, and raise its
  `deadzone` if the stick still drifts. When you read `getState()` directly, use `p1.input.applyDeadzone(value, 0.12)`.
- **`justPressed()` is never true.** Call `actions.update()` exactly once per frame, before you read any action.
  Calling it twice per frame clears the press before the game reads it. Not calling it at all means nothing ever
  changes.
- **A press fires twice, or rumble does not stop.** Create one hub per page and share it. React StrictMode runs
  effects twice in development, so create the hub in an effect and dispose of it in the cleanup. See the
  [React recipe](https://gamepadly.com/sdk/recipes/react).

## Space or the arrow keys scroll the page

An action map calls `preventDefault()` for the Space, arrow and Tab keys it binds, unless focus is in a form field.
Your own keyboard handlers have to call it themselves. Key events from the bridge never
scroll the page: browsers do not run a key's default action for events created by a script.

## WebHID: DualSense triggers and Switch Pro HD Rumble

### The connect button throws in Firefox or Safari

These browsers do not have WebHID, and `hub.connectWebHID()` throws `WebHID requires a Chromium browser` there.
Show the button only where it can work. Everything else in the SDK keeps working without it:

```ts
connectButton.hidden = !('hid' in navigator);
```

### The picker does not open

Browsers show the device picker only in response to a click or key press. Call `hub.connectWebHID()` from the
click handler itself, not on page load and not after an `await` that takes long. Outside a click the call fails:
depending on the browser it rejects with a `SecurityError` or resolves `false`.

### It fails inside an iframe

If the game runs in an iframe from another origin, as on game portals and in CodePen or CodeSandbox previews,
Chromium blocks WebHID unless the embedding page allows it:

```text
SecurityError: Failed to execute 'requestDevice' on 'HID': Access to the feature "hid" is disallowed by permissions policy.
```

The page that embeds the game has to add `allow="hid"` to the iframe:

```html
<iframe src="https://game.example.com/" allow="hid"></iframe>
```

Chromium allows the Gamepad API, which carries input and standard rumble, in cross-origin iframes by default, so
the game stays playable without the attribute. If you do
not control the embedding page, such as a portal like itch.io (_not tested_), offer WebHID only when the game is
opened in its own tab.

### The controller is not in the picker

The picker lists only the controllers WebHID can upgrade: DualSense, DualSense Edge and the Switch Pro Controller.
DualShock 4, Joy-Con and Xbox controllers are not listed. Xbox controllers do not need WebHID: rumble and trigger
motors work through the standard Gamepad API.

### Connecting fails after the picker

`connectWebHID()` rejects when the browser cannot open the device, for example while another program holds it
(_not tested_). Catch the error so a failed upgrade never stops the game:

```ts
connectButton.addEventListener('click', async () => {
  try {
    const connected = await hub.connectWebHID(); // false when the player closes the picker
    if (!connected) return;
  } catch (error) {
    showMessage('Could not connect the controller. Close other controller apps and try again.');
    console.warn(error);
  }
});
```

After a page reload, call `hub.reconnectAuthorized()` to reattach controllers the player already approved, with no
picker.

## Haptics

- **Every call returns `'none'`.** No controller is detected yet (see above), or the browser exposes no rumble
  motor for this controller. `caps.matrix.dual_motor_rumble.reason` says which.
- **Xbox rumble plays, but not the trigger motors.** The call returns `'dual_rumble'` instead of
  `'impulse_triggers'`. Trigger motors need Chrome or Edge 126 or later. Windows Bluetooth can block them, so
  connect over USB or the Xbox Wireless Adapter if they stay silent.
  `caps.matrix.impulse_triggers.reason` explains the current controller.
- **Adaptive triggers do not resist.** They need a DualSense connected over WebHID. Trigger calls made before the
  connection do nothing, so apply the effect again when the connection changes:

  ```ts
  const p1 = hub.player(0);
  const applyTriggers = () => p1.triggers.applyPreset('weapon', 'right');
  applyTriggers();
  hub.onCapabilitiesChange(applyTriggers);
  ```

  A bridge profile with a `triggers` entry does this for you when the bridge is given the hub (`player: hub`).
- **Rumble or trigger resistance stays on after the game ends.** Call `hub.dispose()` when the game's view goes
  away. The SDK also stops rumble and resets the triggers when the page closes.

## Tests and server rendering

- **Server rendering and Node.** The SDK can be imported in Node, and `createGamepadly()` works there without
  `navigator`: it reports `'keyboard_mouse'` and its haptic calls return `'none'`. You do not need to guard the
  import. `connectWebHID()` throws in Node, so call it only from a click.
- **A test presses `south` and nothing happens.** Mock state uses the base button names. Set
  `state.buttons.cross` for `south`, `circle` for `east`, `square` for `west` and `triangle` for `north`. See
  [Test it without a controller](https://gamepadly.com/sdk/start/add-controller#7-test-it-without-a-controller).

## Optional 4-channel audio

The DualSense speaker and its 4-channel haptics need Windows and a USB connection. The connect functions return a
typed error such as `link_not_running` or `dualsense_audio_not_found`. Each error is explained in
[Permissions and failure modes](https://gamepadly.com/sdk/compatibility#3-permissions--failure-modes), and the setup is in
[Optional Link](https://gamepadly.com/sdk/guides/link).

## Still stuck

[Open an issue](https://github.com/gamepadly/gamepadly-sdk/issues) with:

- the browser and its version, and the operating system;
- the controller and how it is connected (USB, Bluetooth or a wireless adapter);
- what the snippet at the top of this page logged;
- whether the [online controller tester](https://gamepadly.com/) sees the controller.

Results from browsers, systems and controllers we have not tested are welcome too: they decide what the
[compatibility matrix](https://gamepadly.com/sdk/compatibility) marks as verified.
