Ways to make Javascript code hacking / injection / manipulation difficult?

后端 未结 4 977
情深已故
情深已故 2021-02-06 08:37

Are there ways to prevent, or make it difficult enough, for someone to inject Javascript and manipulate the variables or access functions? A thought I had is to change all var n

相关标签:
4条回答
  • 2021-02-06 08:51

    Any user that will really want to tamper with the client will be able to. The code is on his machine. Even if you obfuscate the client side code, there are tools out their that will help someone deobfuscate the code back in a second.

    What you need to think about though is making the site safe on the server, and safe for other users as well. This means (as a minimum):

    1. Checking/Validating every request and input parameters on the server so Users won't be able to alter any server side data by triggering 'hacked' client side functions you wrote.

    2. Check all data that you output to the screen that was originated from user input. Other users might have inserted client side scripts that are dangerous for your site, and especially dangerous to the other users on your site. (If you're using .net then check out the AntiXSS library)

    0 讨论(0)
  • 2021-02-06 08:57

    Accept that your javascript will be "manipulated" and make provision at the server side. There's fundamentally nothing you can do to stop people tinkering with the client.

    0 讨论(0)
  • 2021-02-06 09:00

    Obfuscation and minification should make it a good bit more difficult to hack, but I agree with spender.

    0 讨论(0)
  • 2021-02-06 09:10

    You can write your JS to use only private methods and variables in a self-executing function. For example, the following code leaves no sign of itself in the global namespace for anyone to monkey with.

    (function(){
        var x = 1;
        var y = 2;
        var z = "A am z";
        var clickHandler = function() {
            alert('You clicked the body');
        };
        document.getElementsByTagName('body')[0].addEventListener('click',clickHandler,true);
    }());
    

    [EDIT] The above code is susceptible to a user overwriting any globally available objects, methods, events or properties you are using (in this case, document, getElementsByTagName and addEventListener), so if you are truly paranoid you can copy these to your function scope before the page has loaded and the user has a chance to overwrite them. Using addEventListener is a good idea because unlike the event body.onclick, it cannot be removed or overwritten from outside the function.

    0 讨论(0)
提交回复
热议问题