前端禁止打开开发者工具,及各种屏蔽功能的实现
我们的网页常常会被人扒源码,辛辛苦苦写的内容被人复制,很是苦恼,用了下面代码可以完美有效屏解决。
禁止打开开发者工具
检测原理
通过检测视口高度,来判断是否打开了开发者工具。
检测代码
(function () {
'use strict'
var devtools = {
open: false,
orientation: null
}
var threshold = 160
var emitEvent = function (state, orientation) {
window.dispatchEvent(new CustomEvent('devtoolschange', {
detail: {
open: state,
orientation: orientation
}
}))
}
setInterval(function () {
var widthThreshold = window.outerWidth - window.innerWidth > threshold
var heightThreshold = window.outerHeight - window.innerHeight > threshold
var orientation = widthThreshold ? 'vertical' : 'horizontal'
if (!(heightThreshold && widthThreshold) && ((window.Firebug && window.Firebug.chrome && window.Firebug.chrome.isInitialized) || widthThreshold || heightThreshold)) {
if (!devtools.open || devtools.orientation !== orientation) {
emitEvent(true, orientation)
}
devtools.open = true
devtools.orientation = orientation
} else {
if (devtools.open) {
emitEvent(false, null)
}
devtools.open = false
devtools.orientation = null
}
}, 500)
if (typeof module !== 'undefined' && module.exports) {
module.exports = devtools
} else {
window.devtools = devtools
}
})();调用:
window.addEventListener('devtoolschange', function (e) {
if (e.detail.open){
document.getElementsByTagName('body')[0].innerhtml = '<style>body{height:100vh;display:flex;justify-content:center;align-items:center}h1{text-align:center;font-size:50px;color:#ccc;cursor:default}</style><h1>禁止使用开发者工具</h1>';
}
})调式则提示Paused in debugger
(function (a) {
return (function (a) {
return (Function('Function(arguments[0]+"' + a + '")()'))
})(a)
})('bugger')('de', 0, 0, (0, 0));屏蔽F12 审查元素
<script>
document.onkeydown = function () {
if (window.event && window.event.keyCode == 123) {
alert("F12被禁用");
event.keyCode = 0;
event.returnValue = false;
}
if (window.event && window.event.keyCode == 13) {
window.event.keyCode = 505;
}
if (window.event && window.event.keyCode == 8) {
alert(str + "\n请使用Del键进行字符的删除操作!");
window.event.returnValue = false;
}
}
</script>屏蔽右键菜单
document.oncontextmenu = function (event){
window.event.returnValue = false;
}屏蔽粘贴
document.onpaste = function (event){
window.event.returnValue = false;
}屏蔽复制
document.oncopy = function (event){
window.event.returnValue = false;
}屏蔽剪切
document.oncut = function (event){
window.event.returnValue = false;
}屏蔽选中
document.onselectstart = function (event){
window.event.returnValue = false;
}本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!