Prevent users from opening HTML pages for debugging

【Foreword】

      During the winter vacation, I watched dramas at home for a few days. When I watched "Han Zhu Gege" on a small website, I felt that the page layout and compatibility were very good, so I wanted to check the code, but I didn't expect it to be blocked.

      I mentioned it before, but I suddenly thought of it today, here is how to prohibit debugging code

 

【Introduction】

       Sometimes, we may want to prohibit users from modifying or debugging the code of our HTML page. At this time, we need to organize users to open the debugging window. Here are some methods that can prevent users from opening the debugging window in the browser. These methods can only be used to a certain extent. Raising the threshold for enabling debugging cannot completely eliminate it.

 

【List】

(1) Disable F12

(2) Disable the right button

(3) Disable pre-debugging

 

【Details】

(1) Disable F12

   For the method of using F12 to open the debug window, we only need to register the processing method of the F12 button and prevent the default event behavior:

window.onkeydown = window.onkeyup = window.onkeypress = function (event) {
    // Determine whether to press F12, the F12 key code is 123
    if (event.keyCode = 123) {
        event.preventDefault(); // prevent default event behavior
        window.event.returnValue = false;
    }
}

 

(2) Disable the right button

   For the behavior of using the right-click menu and selecting view source code in the right-click menu, we only need to override the behavior of the click event of the right-click menu:

// Add a custom event for the right button, which can be disabled
window.oncontextmenu = function() {
    event.preventDefault(); // prevent default event behavior
    return false;
}

 

(3) Disable pre-debugging

      Even if F12 and right click are disabled at the same time, there are other ways to open the debug window, for example:

   ①Open the debug window in advance, and then enter the URL in the address, so that the debug window is opened even if you don't need to right-click and F12;

   ②Open the developer tools through the browser menu to open the debug window, and shortcut keys such as shift+ctrl+i to open the console

对于这种预先打开调试窗口的方法,我们可以通过比较屏幕 window.outerWidth 和页面可见内容区域 window.innerWidth 的差距判断是否打开控制台

var threshold = 160; // 打开控制台的宽或高阈值
// 每秒检查一次
window.setInterval(function() {
    if (window.outerWidth - window.innerWidth > threshold || 
    window.outerHeight - window.innerHeight > threshold) {
        // 如果打开控制台,则刷新页面
        window.location.reload();
    }
}, 1e3);

    这种方法对于像IE8这种,打开调试窗口是在一个新的Windows窗口中,而不是在当前页面的下面或者上面的情况会失效。

  

【拓展】

      (1)这里我用的是setInterval函数,关于setInterval(设置间隔)和setTimeout(设置超时),我在下篇文章做下区别和介绍

 

 

 

 

 

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326086646&siteId=291194637