使用 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
Obtaining canonical url using JavaScript
提问by Tereno
采纳答案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.html
if you don't have full URL.
以上 answear 将为您提供 href 属性的真实值。因此,/query.html
如果您没有完整的 URL,它会向您显示 href 。
But .href
method 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")