While Onanism has become a synonym for masturbation, read the passages again. It could just as easily be that Onan was using the withdrawal method, a very risky mode of birth control but nevertheless a reasonable interpretation based on the description in the passages.
Okay, let's assume that's true. If that is the correct interpretation (i.e. that the withdrawal method is a sin), then how could masturbation not also be immoral?