Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Set Canonical URL via Javascript
<script type='text/javascript'>
var link = !!document.querySelector("link[rel='canonical']") ? document.querySelector("link[rel='canonical']") : document.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('href', location.protocol + '//' + + location.pathname);
Copy link

andrei0207 commented Jul 9, 2019

i have tried this code and it works as i see it in my page source, Thanks man

Copy link

allanderek commented Jul 19, 2019

Shouldn't you delete any existing canonical links?

Copy link

krschmidt commented Jul 20, 2019

Probably a good idea. Updated to rewrite the existing link element if it's present. Though this whole gist generally feels like a hack.

Copy link

bareddyyaminireddy commented Jan 22, 2021

**** metaInfo: {
link: [{ rel: "canonical", href: ${window.location} }]
} ***

we can directly add it in router if you are using vue js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment