简体   繁体   中英

How to prevent malicious code from calling my javascript

I have this code inside a file located at http://example.com/analytics.js and referenced in the HMTL head. The below code is kind of Javascript pseudo code to what I want to do

function collectStatistics(){
    // this function will send the page view to my server
    recordPageView(window.location.href);
}

How can I prevent malicious code and spammers from abusing my recordPageView function? Simplest thing they can do is to put it inside a loop in the browser console and if I throttle it, they can put a timer inside the loop ... etc

Thanks

You can't. Client-side code is entirely hackable, full stop. Anyone viewing the page can readily trigger calls to collectStatistics , in a loop or otherwise. Or they can take it a step further, see what you're sending in recordPageView , and do it directly.

All you can do is track this stuff server-side and look for patterns of abuse, which is exactly what Google and others do with their ad networks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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