禁用浏览器右键菜单等操作
- 2019 年 11 月 5 日
- 筆記
防止用户在浏览器中打开右键菜单、文本选中、复制内容、F12打开控制台的操作
右键菜单
document.oncontextmenu = function (event) { event.preventDefault(); };
文本选中
if(document.all){ document.onselectstart= function(){return false;}; //for ie }else{ document.onmousedown= function(){return false;}; document.onmouseup= function(){return true;}; } document.onselectstart = new Function('event.returnValue=false;');
-moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; -khtml-user-select: none; user-select: none;
复制内容
document.oncopy = function (event) { if (window.event) { event = window.event; } try { var the = event.srcElement; if (!((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) { return false; } return true; } catch (e) { return false; } }
F12打开控制台
document.onkeydown = document.onkeyup = document.onkeypress = function(event) { var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && e.keyCode == 123) { e.returnValue = false; return (false); } }
检测用户打开控制台后强制跳转
var ConsoleManager = { onOpen: function() { alert('Console is opened'); }, onClose: function() { alert('Console is closed'); }, init: function() { var self = this; var x = document.createElement('div'); var isOpening = false, isOpened = false; Object.defineProperty(x, 'id', { get: function() { if (!isOpening) { self.onOpen(); isOpening = true; } isOpened = true; } }); setInterval(function() { isOpened = false; console.info(x); console.clear(); if (!isOpened && isOpening) { self.onClose(); isOpening = false; } }, 200); } }; ConsoleManager.onOpen = function() { //打开控制台,跳转到百度 try { window.open('https://www.baidu.com/', (target = '_self')); } catch (err) { var a = document.createElement('button'); a.onclick = function() { window.open('https://www.baidu.com', (target = '_self')); }; a.click(); } }; ConsoleManager.onClose = function() { alert('Console is closed!!!!!'); };