Pus*_*kin 4 javascript browser security reactjs
顾名思义,开发人员工具应该仅在开发过程中可见或可访问,而不是在生产过程中。我不希望我的最终用户看到状态和组件树,从而知道幕后发生了什么。尽管生产中的 React Developer Tool 既不允许修改组件的状态,也不会显示它们的名称,但它并没有完全隐藏它们或完全禁用这些工具。最终用户仍然可以看到每个组件的状态和整个应用程序树。
有没有办法排除/禁用 React Developer 工具或在生产构建中断开它,就像 Augury 对 Angular 所做的那样?
当我在互联网上寻找答案时,这个问题仍处于草稿阶段,我发现了这个。但遗憾的是这没有用。但它确实告诉我,这与 有关__REACT_DEVTOOLS_GLOBAL_HOOK__。
所以在玩了它并修改它之后,它起作用了。它成功地断开了应用程序与 React Developer Tools 的连接。
以下是将应用程序与 React 开发人员工具断开连接的代码。
// disableReactDevTools.ts
// Declare the types if you're using TypeScript
// Ignore this block if you're using JavaScript
declare global {
interface Window {
__REACT_DEVTOOLS_GLOBAL_HOOK__: any;
}
}
export function disableReactDevTools() {
// Check if the React Developer Tools global hook exists
if (typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__ !== "object") {
return;
}
for (const prop in window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
if (prop === "renderers") {
// initialise this with an empty `Map`,
// else it will throw an error in console
window.__REACT_DEVTOOLS_GLOBAL_HOOK__[prop] = new Map()
} else {
// Replace all of its properties with a no-op function or a null value
// depending on their types
window.__REACT_DEVTOOLS_GLOBAL_HOOK__[prop] =
typeof window.__REACT_DEVTOOLS_GLOBAL_HOOK__[prop] === "function"
? () => {}
: null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
// index.tsx
import React from "react";
import ReactDOM from "react-dom";
// ...
if (process.env.NODE_ENV === "production") disableReactDevTools();
// ...
Run Code Online (Sandbox Code Playgroud)
此代码不会在控制台中引发任何错误或警告。
| 归档时间: |
|
| 查看次数: |
6754 次 |
| 最近记录: |