前端禁止f12等进入开发者模式
说明:前台无法处理安全性的问题,无法完全封闭开发者模式,甚至攻击者抓包直接使用接口调试工具或者代码请求,因此应该在后端进行严格的限制
1.创建文件 disableDevTools.js
// src/disableDevTools.js
// 禁用 F12 和其他开发者工具快捷键
document.addEventListener('keydown', (e) => {
// 禁用 F12
if (e.keyCode === 123) {
e.preventDefault();
e.returnValue = false;
}
// 禁用 Ctrl+Shift+I (检查元素)
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.keyCode === 73) {
e.preventDefault();
e.returnValue = false;
}
// 禁用 Ctrl+Shift+J (打开控制台)
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.keyCode === 74) {
e.preventDefault();
e.returnValue = false;
}
// 禁用 Ctrl+U (查看页面源代码)
if ((e.ctrlKey || e.metaKey) && e.keyCode === 85) {
e.preventDefault();
e.returnValue = false;
}
// 禁用 Ctrl+Shift+C (检查元素)
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.keyCode === 67) {
e.preventDefault();
e.returnValue = false;
}
});
// 禁用右键菜单,防止通过右键检查元素
document.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
// 检测开发者工具是否打开
(function () {
const devtools = {
open: false,
orientation: null,
};
const threshold = 160;
const emitEvent = (isOpen, orientation) => {
window.dispatchEvent(new CustomEvent('devtoolschange', {
detail: {
open: isOpen,
orientation,
},
}));
};
const main = ({ emitEvents = true } = {}) => {
const widthThreshold = window.outerWidth - window.innerWidth > threshold;
const heightThreshold = window.outerHeight - window.innerHeight > threshold;
const orientation = widthThreshold ? 'vertical' : 'horizontal';
if (
!(heightThreshold && widthThreshold)
&& ((window.Firebug && window.Firebug.chrome && window.Firebug.chrome.isInitialized) || widthThreshold || heightThreshold)
) {
if ((!devtools.open || devtools.orientation !== orientation)) {
devtools.open = true;
devtools.orientation = orientation;
if (emitEvents) {
emitEvent(true, orientation);
}
}
} else {
if (devtools.open) {
devtools.open = false;
devtools.orientation = null;
if (emitEvents) {
emitEvent(false, null);
}
}
}
};
main({ emitEvents: false });
setInterval(main, 500);
window.addEventListener('devtoolschange', (e) => {
if (e.detail.open) {
alert('请不要打开开发者工具!');
window.location.href = 'https://www.baidu.com';
//
// for (let i = 0; i < 10; i++) {
// window.open('https://www.baidu.com', '_blank');
// }
// 尝试关闭当前页面(可能不成功)
window.close();
// window.location.reload(); // 开发者工具打开时刷新页面或其他操作
}
});
}());
- main.js引入对应文件
import './disableDevTools'; // 引入禁用开发者工具的逻辑
3.打开浏览器进行测试
评论区