> 文章列表 > Web前端如何防止被恶意调式?

Web前端如何防止被恶意调式?

Web前端如何防止被恶意调式?

前言

为什么要防止被恶意调式?

我们的目的是尽可能的减少资源盗取,爬虫和攻击 api !

具体实现

第一种方式:禁止F12和右击、审查元素设置中强行打开开发者会直接关闭网页

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>防爬虫</title><script>//禁用右键(防止右键查看源代码)window.oncontextmenu = function() {return false;}//禁止任何键盘敲击事件(防止F12和shift+ctrl+i调起开发者工具)window.onkeydown = window.onkeyup = window.onkeypress = function() {window.event.returnValue = false;return false;}//如果用户在工具栏调起开发者工具,那么判断浏览器的可视高度和可视宽度是否有改变,如有改变则关闭本页面var h = window.innerHeight,w = window.innerWidth;window.onresize = function() {if (h != window.innerHeight || w != window.innerWidth) {window.close();window.location = "about:blank";}}</script></head><body><h1>hello</h1></body>
</html>

第二种方式:使用开源项目ConsoleBan

Github:https://github.com/fz6m/console-ban/blob/master/README.zh.md

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>防爬虫</title><script src="https://cdn.jsdelivr.net/npm/console-ban@5.0.0/dist/console-ban.min.js"></script><script>// 第一种防爬虫的方法,打开F12自动重定向// ConsoleBan.init({// 	redirect: '/404'// })//第二种防爬虫的方法,重写页面元素var div = document.createElement('div')div.innerHTML = '<h1> 不要偷看啦~</h1>'ConsoleBan.init({// 重写 body 为字符串write: '<h1> 不要偷看啦~ </h1>',// 可传入节点对象write: div})//第三种防爬虫的方法,打开F12自动走debuggerConsoleBan.init({debug: true,debugTime: 1})</script></head><body><h1>hello</h1></body>
</html>

主要是通过ConsoleBan.init()进行实例化,跟Vue实例化用法类似,该对象可传参数如下:

参数名 必须 类型 默认值 描述
clear no boolean true 禁用 console.clear 函数
debug no boolean true 是否开启定时 debugger 反爬虫审查
debugTime no number 3000 定时 debugger 时间间隔(毫秒)
redirect no string - 开启控制台后重定向地址
write no string | Element - 开启控制台后重写 document.body 内容,支持传入节点或字符串
callback no Function - 开启控制台后的回调函数
bfcache no boolean true 禁用 bfcache 功能

第三种方式:自动清空控制台

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>防爬虫</title><script>var clear = console.clearsetTimeout(clear, 1)</script></head><body><h1>hello</h1></body>
</html>

总结

1.三种方式都很好用,具体使用那种方式进行防范可以根据自己实际需求进行选定!

2.笔者能力有限,希望有经验的大神能在评论区提供更多的方式方法!