Skip to content

Instantly share code, notes, and snippets.

@Sominemo
Last active May 17, 2021 16:11
Show Gist options
  • Save Sominemo/64802ddea0ceec014e0a844e149eed48 to your computer and use it in GitHub Desktop.
Save Sominemo/64802ddea0ceec014e0a844e149eed48 to your computer and use it in GitHub Desktop.
DevTools Detector

DevTools Detector

Function detectDevTools

  • Return type: Object
{
  bool isOpen, // true if DevTools are open
  enum["vertical", "horizontal", null] orientation, // Orientation of the pane. null if isOpen is false
}

Constructor DevToolsListener(int? interval)

Starts listening for DevTools state changes each specified interval. interval defaults to 500.

Event of type CustomEvent("devtoolschange") is being pushed on window as a result. Events start to come after the next change, there's no initialization event. The event contains detail field with detectDevTools call result and source property, which contains the constructor.

  • Return type: Constructor
{
  Object lastState, // Last return value of detectDevTools()
  Function disconnect(), // Stop listening for changes
}

Example of use

// Start listening for the changes once per second
new DevToolsListener(1000);

// Set event
window.addEventListener('devtoolschange', function (e) {
  // Ignore if DevTools are not open
  if (!e.detail.isOpen) return; 

  // Stop listening
  e.detail.source.disconnect();
  // Output orientation
  console.log(e.detail.orientation)
});
function detectDevTools() {
let h = window.outerWidth - window.innerWidth > 160;
let v = window.outerHeight - window.innerHeight > 160;
if (
(h && v) ||
!((window.Firebug && window.Firebug.chrome && window.Firebug.chrome.isInitialized) || h || v)
) {
return { isOpen: false, orientation: null };
}
return { isOpen: true, orientation: h ? "vertical" : "horizontal" };
}
function DevToolsListener(interval) {
if (!new.target) return new DevToolsListener(interval);
this.lastState = detectDevTools();
const i = setInterval(() => {
let cur = detectDevTools();
if (this.lastState.isOpen !== cur.isOpen || this.lastState.orientation !== cur.orientation) {
this.lastState = cur;
window.dispatchEvent(
new CustomEvent("devtoolschange", {
detail: {
isOpen: this.lastState.isOpen,
orientation: this.lastState.orientation,
source: this,
},
})
);
}
}, interval || 500);
this.disconnect = function () {
clearInterval(i);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment