I'm building a website internally and the page has a canonical URL set in the <head>
that specifies the page's URL externally.
Is there any way to use JavaScript to obtain the canonical URL?
Canonical URL helps the search engines that certain similar URLs are actually one and the same. This solves the duplicate content problem where search engines don't know which version of the content to show.
A canonical URL is the URL of the best representative page from a group of duplicate pages, according to Google. For example, if you have two URLs for the same page (such as example.com? dress=1234 and example.com/dresses/1234 ), Google chooses one as canonical.
A self-referencing canonical tag, as it sounds, is one that canonicals to itself. This ensures that multiple versions of the page (duplicates) don't get indexed separately. For example, the page https://www.example.com would have a rel=”canonical” tag that points to https://www.example.com (the same URL).
Well nowadays you can simply use:
document.querySelector("link[rel='canonical']").getAttribute("href");
The above answear will give you true value of href attribute. So it will show you href like /query.html
if you don't have full URL.
But .href
method will give you always full URL with domain like http://example.com/query.html
:
document.querySelector("link[rel='canonical']").href;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With