1、禁用鼠标的右键菜单
document.addEventListener("contextmenu", e => e.preventDefault())
2、拦截键盘的快捷键
- F12 控制台
- Ctrl + Shift + I 控制台 console
- Ctrl + Shift + C 控制台 elements
- Shift + F10 鼠标右击
- Ctrl+U 查看源码
document.addEventListener('keydown', (e) => {
// 禁止f12,禁用ctrl+shift+i,c,禁用shift+f10
const code = e.code
const ctrl = e.ctrlKey
const shift = e.shiftKey
const isCSI = ctrl && shift && code === 'KeyI'
const isCU = ctrl && code === 'KeyU'
const isF12 = code === 'F12'
const isCSC = ctrl && shift && code === 'KeyC'
const isSF10 = shift && code === 'F10'
if ( isF12 || isCSI || isCSC || isSF10 || isCU) {
e.preventDefault()
}
})
3、使用浏览器设置 找到开发者工具 - 控制台
- 检测浏览器宽度变化
- 无法阻止 直接跳转到空白页面,让用户无法使用
let lastWidth = window.innerWidth
let lastHeight = window.innerHeight
window.addEventListener("resize", () => {
const widthDiff = Math.abs(window.innerWidth - lastWidth)
const heightDiff = Math.abs(window.innerHeight - lastHeight)
// 如果窗口尺寸变化但不是全屏切换,可能是控制台打开
if ((widthDiff > 50 || heightDiff > 50) && !isFullScreen()) {
//跳转到空白页面
window.location.href = "about:blank"
alert("检测到异常窗口变化,请关闭开发者工具")
}
lastWidth = window.innerWidth
lastHeight = window.innerHeight
})
function isFullScreen() {
return (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.msFullscreenElement
)
}
4、提前打开了控制,再访问页面
- 监听当前可视区域的宽高,来判断是否打开了浏览器开发者工具,你打开控制台 可视区域肯定变小了
- window.innerWidth:表示浏览器窗口的内部宽度,即可视区域的宽度。这个宽度不包括滚动条,但包括任何边框(border)和内边距(padding),即是指可视区域内可用于显示文档的宽度,单位为像素
- window.outerWidth: 表示浏览器窗口的外部宽度,即整个浏览器窗口的宽度,包括滚动条、边框和窗口周围的任何其他元素。这个宽度是整个浏览器窗口的宽度,包括浏览器窗口自身的宽度、浏览器菜单栏、工具栏、状态栏以及其他附加组件的宽度。
- 当然 如果让控制悬浮了 这就不行了
window.addEventListener('resize', function () {
if (window.outerWidth - window.innerWidth > 0 || window.outerHeight - window.innerHeight > 130) {
console.log("开发者工具已打开!");
location.href = "about:blank"
}
});
- 无限Debugger:通过 Function("debugger") 来动态生成断点(动态生成是为了防断点禁用),通过无限循环生成断点,让页面一直处于断点状态
(() => {
function block() {
setInterval(() => {
(function(){return false;})["constructor"]("debugger")["call"]();
}, 50);
}
try { block(); } catch (err) {}
})();
其他:disable-devtool、devtools-detector、等
总结:无法完全阻止,只是增加难度,针对小白效果还不错,真懂技术的没啥效果