AEPKILL / devtools-detector

Detect if DevTools is open
https://blog.aepkill.com/demos/devtools-detector/
MIT License
1.11k stars 104 forks source link

launch() doesnt work if we navigate keeping the developer tools already open #69

Closed mohiyuddinshaikh closed 7 months ago

mohiyuddinshaikh commented 7 months ago

The library works perfectly when you open the devtools. But say in my react app, i am on page A where devtools is allowed. So devtools is open. I then navigate to page B where devtools is not allowed and where I am using the library, but this time it doesnt detect that devtools was already open and hence user can access dev tools where I dont want them to.

AEPKILL commented 7 months ago

You need to remember the previous status of devtools because the message won't trigger unless devtools status has changed.

import { useSyncExternalStore, useEffect } from "react";
import devtoolsDetector from "devtools-detector"; // version: 2.0.16

const devtoolsStatusStore = {
  subscribe(callback: () => void) {
    const isLaunched = devtoolsDetector.isLaunch();
    devtoolsDetector.addListener(callback);
    if (!isLaunched) {
      devtoolsDetector.launch();
    }
    return () => {
      devtoolsDetector.removeListener(callback);
      if (!isLaunched) {
        devtoolsDetector.stop();
      }
    };
  },
  getIsOpen() {
    return devtoolsDetector.isOpen;
  },
};

export function useDevtoolsIsOpen() {
  return useSyncExternalStore(
    devtoolsStatusStore.subscribe,
    devtoolsStatusStore.getIsOpen
  );
}

Example