Raf*_*ski 52
那么现在你可以简单地使用:
document.querySelector("link[rel='canonical']").getAttribute("href");
Run Code Online (Sandbox Code Playgroud)
上面的answear将为您提供href属性的真正价值.因此,/query.html如果您没有完整的URL,它会向您显示 .
但是.href方法会给你带有域的完整URL,如http://example.com/query.html:
document.querySelector("link[rel='canonical']").href;
Run Code Online (Sandbox Code Playgroud)
Teo*_*ahi 19
jquery版本;
$("link[rel='canonical']").attr("href")
Run Code Online (Sandbox Code Playgroud)
Alb*_*reo 16
像这样的东西?
<!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>
Run Code Online (Sandbox Code Playgroud)