Refactor onmessage handler