There's a number of inter-related issues here. My approach is that this can be done entirely server-side first, and then a JavaScript improvement added atop such that it doesn't matter if the client-side stuff fails to run.
The core of the solution is to set a last_seen
time on the server when the user logs on. Whenever you detect any user activity (either a page rendering or an AJAX response), check whether this time is within acceptable bounds for you, and if it is overwrite it with the current time. If it is outside of the current bounds, destroy the session on the server side, and force a redirect to the login page, with a suitable message.
Once you have done that, there is no way that server-side value can be tinkered with, unless the user artificially refreshes their page pointlessly in order to avoid the timeout - but in that case, you would be unable to determine the difference between a "real" page request and one designed just to reset the session timer. If you are worried about malicious software on the user's computer, or an advanced man-in-the-middle attack on the user's connection, then you've got bigger problems than session timeout anyway.
Once this is set up, you may wish to use JavaScript to run a timer on each page that automatically shows the logged-off-automatically message. Just set this timer for the same length of time as your timeout, and of course restart it if an AJAX operation is triggered on the page. You could inject this message into the DOM, rather than redirecting, so if the user is filling out a form, they don't lose their work.
As you say, you could always detect form key-strokes to reset the timer. To do so, send an AJAX operation to the server that answers with an empty reply - that will send the cookie automatically - just ensure that your standard session code is run here too. Do use a JavaScript timer so that you don't send an AJAX op for every press - if it sometimes goes ten seconds later than the key press, then you'll not overwhelm the connection and you'll ensure your application remains speedy.