简体   繁体   中英

Prevent React dev tools from changing props/state

Is there a way to prevent any prop/state change from front-end on production?

I tried following but it completely disables the dev tools:

if (typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__ === 'object') {
  for (let [ key, value ] of Object.entries(
    window.__REACT_DEVTOOLS_GLOBAL_HOOK__
  )) {
     window.__REACT_DEVTOOLS_GLOBAL_HOOK__[key] =
       typeof value === 'function' ? () => {} : null;
  }
}    

I use the following bit of code in my Meteor application that uses React 16.3 as the UI library.

The window.__ALLOW_REACT_DEVTOOLS__ is just a flag I set in the SSR html sent from the server because this line of code needs to preclude any React code, and I need it before process.env is available in the browser. On the server I set that value to false in production.

<script>
  if (
    !window.__ALLOW_REACT_DEVTOOLS__ &&
    window.__REACT_DEVTOOLS_GLOBAL_HOOK__ &&
    typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__ === "object"
  ) {
    for (let [key, value] of Object.entries(window.__REACT_DEVTOOLS_GLOBAL_HOOK__)) {
      window.__REACT_DEVTOOLS_GLOBAL_HOOK__[key] = typeof value == "function" ? ()=>{} : null;
    }
  }

  delete window.__ALLOW_REACT_DEVTOOLS__;
</script>

The key to making this work is that it is loaded BEFORE React.

This will completely disable React-Devtools. When you click on the devtools tab it will just say 'Looking for React...' .

Okay, found a way to keep even that function from getting injected/involved.

I just changed the disabler code to this:

// disable react-dev-tools for this project

 if (typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__ === "object") {
        for (let [key, value] of Object.entries(window.__REACT_DEVTOOLS_GLOBAL_HOOK__)) {
            window.__REACT_DEVTOOLS_GLOBAL_HOOK__[key] = typeof value == "function" ? ()=>{} : null;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM