Skip to content

Instantly share code, notes, and snippets.

@krschmidt

krschmidt/head.html

Last active Aug 10, 2020
Embed
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.host + location.pathname);
document.head.appendChild(link);
</script>
@Nikos-yps

This comment has been minimized.

Copy link

@Nikos-yps Nikos-yps commented Jun 26, 2019

Is this readable from google bots because I can't find it in page source. Thank you

@krschmidt

This comment has been minimized.

Copy link
Owner Author

@krschmidt krschmidt commented Jun 26, 2019

You're not going to find it in the page source though, because it's added to the DOM within the browser, rather than as part of the page source. But I can't say for sure if Google bots would see it - check out this this article for an in depth discussion of if this works.

@Nikos-yps

This comment has been minimized.

Copy link

@Nikos-yps Nikos-yps commented Jun 26, 2019

I've read this article and to be honest I got confused. Although that says Google stated that does not accept or read tags generated with JS in the end canonical urls got passed after a few days.

But those lines made me really skeptical:

The new index coverage report in Google Search Console ignores JS-injected canonical tags in its reports and is thus in line with Google’s official statements.
The reason why Google made an announcement that seems to be wrong might be due to an internal misunderstanding or a bug.

So the only road is to test and see if it works?

@krschmidt

This comment has been minimized.

Copy link
Owner Author

@krschmidt krschmidt commented Jun 26, 2019

Probably. And then to check it again, since Google tends to change things a lot.

@andrei0207

This comment has been minimized.

Copy link

@andrei0207 andrei0207 commented Jul 9, 2019

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

@allanderek

This comment has been minimized.

Copy link

@allanderek allanderek commented Jul 19, 2019

Shouldn't you delete any existing canonical links?

@krschmidt

This comment has been minimized.

Copy link
Owner Author

@krschmidt 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.