What can I do to prevent this in the future?
If you enable JavaScript on by default, change it to disable by default and enable it when you really need it.
JavaScript is used, more often than not, to track your activity or used to effectively inject Malware.
The way to disable JavaScript differs from browsers to browsers, but taking Firefox as an example, using extension uBlock Origin is the handy way. Firefox Add-ons Store.