How to detect whether a headphone is inserted or removed in JavaScript?

You can use the following: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices

example:

navigator.mediaDevices.addEventListener('devicechange', () => {
  // Do whatever you need to with the devices
  // Maybe use enumerateDevices() to see what connected
});

You could check the devices already connected from the following or call it on devicechange:

navigator.mediaDevices.enumerateDevices()
  .then(devices => {
    // Check the connected devices
    console.log(devices);  
  });