I’m not sure if overriding canonical using Javascript will work since this is something that is more on the spider level (i.e. the part that retrieves and collects data) than on the indexer level (the part of a bot that interprets data and stores it in the search index).
Unsolicited advice: you might want to read this topic so you can put those overrides in a plugin: