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

后端 未结 4 986
情深已故
情深已故 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 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.

提交回复
热议问题