@DanielleS your code works really well. Thank you!
I have just made a small adjustment to ensure that the event listener doesn't overwrite other onload handlers.
And yes, according to Google's documentation it is possible to inject a canonical tag with JavaScript.
I hope this helps.