繁体   English   中英

如何防止用户在控制台中执行 js 函数

[英]How to prevent user from executing js function in console

我能做些什么来阻止用户从控制台运行文件中的 js 函数? 我在这里有这个getReward函数:

    function getReward(){

    $('.reward-button').remove();
    $('#rewardBtn').remove();

    document.getElementById("fightInfo").innerHTML = 

    '<strong>You</strong> won the fight.<br><strong>Reward:</strong><br>Gold: ' +gold+' <img src="/img/gold.png" style="margin-top: -1%"><br>EXP: '+exp+'<br>'
    +
    '<br>'
    +
    '<button style="font-size: 24px;" class="btn btn-danger" onclick="backToArena();">⚔️<br>Back To Arena</button>';

    socket.emit('win-fight', {
        gold: gold,
        exp: exp,
        username: userName,
        enemyname: enemyName
    });   

}

    function backToArena(){
        window.location.href = "/arena";
    }

问题是用户只需输入控制台getReward(); 他会自动获得奖励,因为然后套接字工作并且它从客户端转到服务器端。 有没有办法防止这种情况?

更新

 document.getElementById("rewardBtn").innerHTML = 
    '<button style="background-color: blue; font-size: 24px;" class="btn btn-primary" id="reward-button">Get reward 🏆</button>';

然后我这样做:

document.querySelector('#reward-button').addEventListener('click', getReward);

但这不会运行 getReward 函数,没有发生任何错误。

只需将整个脚本包装在IIFE(立即调用函数表达式)中,以便getReward (以及所有其他函数)不在顶层。 顶层的函数(和其他变量)会自动分配给window ,因此只需在控制台中键入函数名即可调用。 但是,如果在另一个函数内声明了一个函数 ,则不会将内部函数赋值给全局对象。

(() => {
  function getReward(){

    $('.reward-button').remove();
    $('#rewardBtn').remove();

    document.getElementById("fightInfo").innerHTML = 

      '<strong>You</strong> won the fight.<br><strong>Reward:</strong><br>Gold: ' +gold+' <img src="/img/gold.png" style="margin-top: -1%"><br>EXP: '+exp+'<br>'
      +
      '<br>'
      +
      '<button style="font-size: 24px;" class="btn btn-danger" onclick="backToArena();">⚔️<br>Back To Arena</button>';

    socket.emit('win-fight', {
      gold: gold,
      exp: exp,
      username: userName,
      enemyname: enemyName
    });   

  }

  function backToArena(){
    window.location.href = "/arena";
  }
})();

在IIFE中包装脚本不仅对安全性有用(不是很好的安全性,而且比开放式控制台和类型函数不安全性更好),而且还为了避免污染全局命名空间,最好避免在可能。

这是魔法

var curWidth = document.documentElement.clientWidth;
var curHeight = document.documentElement.clientHeight;
function consoleCheck()
{
  var temp_curHeight = document.documentElement.clientHeight;
  var temp_curWidth = document.documentElement.clientWidth;

  if(curHeight != temp_curHeight || curWidth != temp_curWidth)
  {
    var devtools = function() {};
    devtools.toString = function() {
    if (!this.opened) {
      $('body').remove();
    }
    this.opened = true;
    }
    console.log('YOU CANNOT HACK THIS SITE');
    console.log('%c', devtools);
  }
  else{
    location.reload();
  }
}

$(window).resize(function () {
  consoleCheck() 
});
$( window ).on( "orientationchange", function( ) {
  consoleCheck()
});

只需在您的项目中添加此脚本,它肯定会停止检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM