基础版防止网站查看源码

前端 2023-01-30

杜绝用户右键查看源码和F12以及ctrl+U

<script>
((function () {
  var callbacks = [],
    timeLimit = 50,
    open = false;
  setInterval(loop, 1);
  return {
    addListener: function (fn) {
      callbacks.push(fn);
    },
    cancleListenr: function (fn) {
      callbacks = callbacks.filter(function (v) {
        return v !== fn;
      });
    }
  }
  function loop() {
    var startTime = new Date();
    debugger;
    if (new Date() - startTime > timeLimit) {
      if (!open) {
        callbacks.forEach(function (fn) {
          fn.call(null);
        });
      }
      open = true;
      window.stop();
      alert('不要看代码啦!');
      window.location.reload();
    } else { open = false; }
  }
})())
  .addListener(function () {
    window.location.reload();
  });
document.oncontextmenu = new Function("event.returnValue=false");
document.onselectstart = new Function("event.returnValue=false");
document.οnkeydοwn = new Function("event.returnValue=false");
document.onkeydown = function (e) {
  if (e && e.keyCode === 123 || e && e.keyCode === 85 || e && e.keyCode === 83) {
    e.returnValue = false;
    return false;
  }
};
</script>