Tereno
Tereno

Reputation: 933

Obtaining canonical url using JavaScript

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?

Upvotes: 28

Views: 31406

Answers (3)

Teoman shipahi
Teoman shipahi

Reputation: 23132

jquery version;

$("link[rel='canonical']").attr("href")

Upvotes: 22

Rafał Malinowski
Rafał Malinowski

Reputation: 1176

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;

Upvotes: 73

Albireo
Albireo

Reputation: 11095

Something like this?

<!DOCTYPE html>
<html>
    <head>
        <link href="http://www.example.com/" rel="canonical" />
        <title>Canonical</title>
        <script type="text/javascript">
            window.onload = function () {
                var canonical = "";
                var links = document.getElementsByTagName("link");
                for (var i = 0; i < links.length; i ++) {
                    if (links[i].getAttribute("rel") === "canonical") {
                        canonical = links[i].getAttribute("href")
                    }
                }
                alert(canonical);
            };
        </script>
    </head>
    <body>
        <h1>Canonical</h1>
    </body>
</html>

Upvotes: 18

Related Questions