开发者

Obtaining canonical url using JavaScript

I'm building a website internally and the page has a canonical URL set in the <head>开发者_如何学C; that specifies the page's URL externally.

Is there any way to use JavaScript to obtain the canonical 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;


jquery version;

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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜