-
-
Save krschmidt/9d46d1d080454b55f8cf to your computer and use it in GitHub Desktop.
<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> |
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.
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?
Probably. And then to check it again, since Google tends to change things a lot.
i have tried this code and it works as i see it in my page source, Thanks man
Shouldn't you delete any existing canonical links?
Probably a good idea. Updated to rewrite the existing link element if it's present. Though this whole gist generally feels like a hack.
**** metaInfo: {
link: [{ rel: "canonical", href: ${window.location}
}]
} ***
we can directly add it in router if you are using vue js.
Just to add to the above statement about Vue, I believe that to do this, you need vue-meta
installed which currently not supported for Vue 3.0 which new projects ought to be using. With that said, vue-meta looks as though it's not going to make it off the runway.
@SamMakesCode Alternative to vue-meta
. I used Unhead
, in VueJS 3 which works fine for the meta title, description and og tags.
@shaheeriversion out of curiousity, how did you accomplish this with unhead
in VueJS 3? I'm trying to set up a project and would love to get canonical link
tags and og:url
meta tags working.
Is this readable from google bots because I can't find it in page source. Thank you