From the cfaa perspective this is potentially fine, from the gdpr perspective probably not.
For a cfaa violation, it would be necessary to show that authorization was exceeded. But the user has implicitly authorized the website to run JavaScript in the browser, and the user has willingly entered information into the website.
In the US context, it might be more interesting that such scripts could be a PCI-DSS violation on pages that process credit card information, but that is a contractual/civil and not a criminal issue.
If the website is in scope of the ccpa/CPRA or similar state-level privacy laws, further limitations might apply.
In the united-kingdom and european-union context, things are very different.
Per gdpr, collection of personal data is permissible e.g. when it is necessary for a legitimate interest which outweighs the data subject's interests. In some cases, collection of data for analytics purposes might be covered by this. But since most users would not reasonably expect keystroke capturing or similarly invasive tracking, it would be difficult to show that the legitimate interest actually outweighs the data subject's rights and interests. On that basis alone, use of such techniques would likely require consent, that is: an informed and freely given unambiguous opt-in decision by the user. Consent is never the default.
But the GDPR is not the most relevant law at play. Instead, the ePrivacy directive (and its implementation PECR in the UK) prohibts access to information stored on the end user's device unless either this access is strictly necessary for a service explicitly requested by the user, or if the user gave consent. Per common interpretation, keylogging is access to information stored on the device. Such invasive tracking is not strictly necessary to deliver the website. Thus, ePrivacy effectively requires consent in this context.
So in an UK/EU context, such trackers/keyloggers would only be lawful with consent. The GDPR's definition of consent which applies here is a fairly high bar to clear – a mere notification of the sort “by using this site you consent to XXX” is not valid. To make an informed decision, the user must first be able to understand what data will be collected for which purposes. Consent must be specific for a purpose, so consent e.g. for ad personalization likely cannot be bundled together with consent for keystroke/mouse logging. A potentially compliant way to use such tracking could be to invite some users into a focus group, and to only load the invasive tracking code after the user has explicitly given informed consent.