禁用浏览器右键菜单等操作

2019-11-02 13:45:26

防止用户在浏览器中打开右键菜单、文本选中、复制内容、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!!!!!');
};
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~