网站常用禁止指令

117 阅读1分钟

1.禁止网站内容选取复制

		
		/*禁止右键*/
		document.oncontextmenu = function(){
			event.returnValue = false;
		}
		// 或者直接返回整个事件
		document.oncontextmenu = function(){
			return false;
		}
		/*禁止选中*/
		document.onselectstart = 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; 
			} 
		}
			
	

2.禁止打开开发者工具

	/*禁止按键相关按键*/
        window.addEventListener('keyup', (event) => {
        document.onkeydown = function (e) {
            if (e.keyCode == 123) {
                alert("F12已被禁用!");
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)) {
                alert("F12已被禁用!");
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)) {
                alert("F12已被禁用!");
                return false;
            }
            if (e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)) {
                alert("F12已被禁用!");
                return false;
            }
            if (e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)) {
                alert("查看源代码已被禁用!");
                return false;
            }
        }

    })
    
  /*当从页面设置打开进入开发者工具时直接跳转空白页  */
  // 根据监听页面变化 浏览器窗口的宽度是否等于窗口的文档显示区的宽度 不等则显示空白页
   function handleResize() {
      const screenWidth = screen.width;
      const windowWidth = window.innerWidth;

      if (screenWidth !== windowWidth) {
        console.log('保护启动');
        document.body.innerHTML = "";
      } else if (screenWidth === windowWidth) {
        console.log('保护解除');
        //location.href="xxxxxxxxxxxx";跳转回页面
      }
    }
 
    // 初始加载时进行一次检查
    handleResize();

    // 添加resize事件监听器
    window.addEventListener('resize', handleResize);