The stellar initial mass function (IMF) represents a fundamental quantity in astrophysics and cosmology describing the mass distribution of stars from low mass all the way up to massive and very massive stars. It is intimately linked to a wide variety of topics, including stellar and binary evolution, galaxy evolution, chemical enrichment, and cosmological reionization. Nonetheless, the IMF still remains highly uncertain. In this work, we aim to determine the IMF with a novel approach based on the observed rates of transients of stellar origin. We parametrize the IMF with a simple but flexible Larson shape, and insert it into a parametric model for the cosmic UV luminosity density, local stellar mass density, type Ia supernova (SN Ia), core-collapse supernova (CCSN), and long gamma-ray burst (LGRB) rates as a function of redshift. We constrain our free parameters by matching the model predictions to a set of empirical determinations for the corresponding quantities via a Bayesian Markov Chain Monte Carlo method. Remarkably, we are able to provide an independent IMF determination with a characteristic mass mc=0.10−0.08+0.24M⊙ and high-mass slope ξ=−2.53−0.27+0.24 that are in accordance with the widely used IMF parameterizations (e.g., Salpeter, Kroupa, Chabrier). Moreover, the adoption of an up-to-date recipe for the cosmic metallicity evolution allows us to constrain the maximum metallicity of LGRB progenitors to Zmax=0.12−0.05+0.29Z⊙. We also find which progenitor fraction actually leads to SN Ia or LGRB emission (e.g., due to binary interaction or jet-launching conditions), put constraints on the CCSN and LGRB progenitor mass ranges, and test the IMF universality. These results show the potential of this kind of approach for studying the IMF, its putative evolution with the galactic environment and cosmic history, and the properties of SN Ia, CCSN, and LGRB progenitors, especially considering the wealth of data incoming in the future.