javascript code to prevent screensaver from starting

No. JavaScript on the browser cannot interact with the underlying system. Simulating keystrokes in the browser will not stop the screen saver from turning on. This is for security reasons, so that malicious code can't harm the system when you visit a web page.

Link on JavaScript Security

The modern JavaScript security model is based upon Java. In theory, downloaded scripts are run by default in a restricted “sandbox” environment that isolates them from the rest of the operating system. Scripts are permitted access only to data in the current document or closely related documents (generally those from the same site as the current document). No access is granted to the local file system, the memory space of other running programs, or the operating system’s networking layer. Containment of this kind is designed to prevent malfunctioning or malicious scripts from wreaking havoc in the user’s environment. The reality of the situation, however, is that often scripts are not contained as neatly as one would hope. There are numerous ways that a script can exercise power beyond what you might expect, both by design and by accident.


Over the decade since this questions question was originally asked JavaScript has grown to provide much of the OS functionality (usually in a secure manner). The "wake lock" functionality is slowly being implemented. Currently there is a draft for the navigator.getWakeLock interface: https://www.w3.org/TR/wake-lock/#conformance

Chrome (https://developers.google.com/web/updates/2018/12/wakelock) and Mozilla (https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API) are considering it in various manners.