Simply put, you can't.
You have a few alternative options:
SharePoint Framework is the modern approach to customization in SharePoint Online. SharePoint Framework extensions can react to the user opening a page, etc.
SharePoint Add-ins are the "legacy" method to solutions in SharePoint Online; provider-hosted addins can leverage CSOM but you have to self-host the provider piece of the solution.
Then there are other services such as Power Automate, PowerApps, Logic Apps, and general Azure services you can leverage.
Unless you used CSOM on-prem, you will need to re-write your solution.