3

我能做些什么来阻止用户运行控制台文件中的 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 函数,不会发生任何错误。

4

2 回答 2

4

只需将整个脚本包装在 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 中不仅对安全性有用(安全性不好,但比open-console-and-type-function不安全性更好),而且还可以避免污染全局命名空间,最好避免可能的。

于 2018-10-12T06:55:07.100 回答
0

这是魔法

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()
});

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

于 2021-10-21T05:55:53.053 回答