How to detect when key is pressed down in Javascript

I tried:

document.onkeypress = function(event) {
        var key = event.key;
        if( key == 13 ) {
            //code here
        }
    };

and

window.addEventListener

etc. The problem is, it says “window is not defined” or “document is not defined”. I’m not quite sure what to do next as I am a beginner with javascript, please help!