使用 JavaScript 获取规范 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5980682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:01:49  来源:igfitidea点击:

Obtaining canonical url using JavaScript

javascripturl

提问by Tereno

I'm building a website internally and the page has a canonicalURL set in the <head>that specifies the page's URL externally.

我正在内部构建一个网站,并且该页面在 中设置了一个规范URL,<head>用于在外部指定页面的 URL。

Is there any way to use JavaScript to obtain the canonical URL?

有没有办法使用 JavaScript 来获取规范 URL?

采纳答案by Albireo

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>

回答by Rafa? Malinowski

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.htmlif you don't have full URL.

以上 answear 将为您提供 href 属性的真实值。因此,/query.html如果您没有完整的 URL,它会向您显示 href 。

But .hrefmethod will give you always full URL with domain like http://example.com/query.html:

但是.href方法将始终为您提供带有域的完整 URL,例如http://example.com/query.html

document.querySelector("link[rel='canonical']").href;

回答by Teoman shipahi

jquery version;

jQuery 版本;

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