You can check out the “user media” object. It can get a list of the connected audio input devices. You can tell if a microphone was pugged in or unplugged based on if the list changed.
For headphones you’d probably have to do that from js to get the output devices too.
developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices