Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining canonical url using JavaScript

Tags:

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?

like image 848
Tereno Avatar asked May 12 '11 15:05

Tereno


People also ask

What is canonical Javascript?

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.

What are canonical URLs?

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.

What is self canonical URL?

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).


1 Answers

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; 
like image 103
Rafał Malinowski Avatar answered Sep 20 '22 20:09

Rafał Malinowski