标签搜索

目 录CONTENT

文章目录

JS实现获取当前页面的URL以及来源URL的方式

沙漠渔
2022-06-23 09:46:21 / 0 评论 / 0 点赞 / 410 阅读 / 1,113 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-06-23,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

鉴于当前发现百度搜索引擎过来的会跳转到对应的评论内容上,所以整理了一下获取来路信息,计划将点击回复跳转到评论功能添加一个限制,如果是搜索引擎过来的就不跳转了,如果是站内点击则跳转,所以有了这篇文章。

Javascript 正常取来源网页的URL方式

新建测试页面index.html:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<title>沙漠渔溏</title>
</head>
<body>
<a href="demo.html">链接</a>
</body>
</html>

新建测试页面demo.html:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<title>沙漠渔溏</title>
</head>
<body>
当前URL:<input type="text" style=" 300px;" name="nowurl" id="nowurl"><br>
来源URL:<input type="text" style=" 300px;" name="fromurl" id="fromurl">
<script>
  var nowurl = document.URL;
  var fromurl = document.referrer;
  document.getElementById('nowurl').value = nowurl;
  document.getElementById('fromurl').value = fromurl;
</script>
</body>
</html>

但,如果来源页是Javascript跳转过来的,上边的方法就拿不到了!所以用:

opener.location.href

var ref = '';  
if (document.referrer.length > 0) {  
	ref = document.referrer;  
}  
try {  
	if (ref.length == 0 && opener.location.href.length > 0) {  
		ref = opener.location.href;  
	}  
} catch (e) {} 

其它相关的说明以及示例效果:

document.URL --"https://www.sammery.com/"
document.referrer -- "https://www.baidu.com/link?url=cg_YZPL-PfhD0ta48C-FxKNESCiUzlQYQ-FUiuLO3CHLuoIU5iMmag2DYi-L8hc1&wd=&eqid=f61d366c004d32c20000000262b3c032"
window.location.href -- "https://www.sammery.com/"
window.location.pathname -- "/"
window.location.host -- "www.sammery.com"
document.domain -- "www.sammery.com"
window.location.protocol -- "https"

0
广告 广告

评论区