js获取来路url和当前url地址实例代码
来源:自学PHP网
时间:2014-09-19 14:47 作者:
阅读:次
[导读] 在js中我们要获取来路url和当前url地址分别直接使用document.referrer与window.location.href即可实现了,下面我来介绍一下实例。...
js获取来路url地址,相当于php的$_SERVER['HTTP_REFERER']。方法:利用js获取来路url地址可以准确地判断网页的真实来路。 目前百度统计,google ads统计,CNZZ统计,都是用的这个方法。防盗链也很简单了,js里判断来路url如果不是本站不显示图片,嘿嘿。
document.referrer
注:js中的referer是referrer不是referer,即:document.referrer,不要写错了,要注意了,呵呵,我也写错过额。
例
代码如下 |
复制代码 |
<table width=100% cellpadding=0 cellspacing=0 border=0 >
<script language="javascript">
thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
strwrite = "<tr><td valign=top>thisURL: </td><td>[" + thisURL + "]</td></tr>"
strwrite += "<tr><td valign=top>thisHREF: </td><td>[" + thisHREF + "]</td></tr>"
strwrite += "<tr><td valign=top>thisSLoc: </td><td>[" + thisSLoc + "]</td></tr>"
strwrite += "<tr><td valign=top>thisDLoc: </td><td>[" + thisDLoc + "]</td></tr>"
document.write( strwrite );
</script>
thisDLoc = document.location; <BR>
thisURL = document.URL; <BR>
thisHREF = document.location.href; <BR>
thisSLoc = self.location.href;<BR>
<script language="javascript">
thisTLoc = top.location.href;
thisPLoc = parent.document.location;
thisTHost = top.location.hostname;
thisHost = location.hostname;
strwrite = "<tr><td valign=top>thisTLoc: </td><td>[" + thisTLoc + "]</td></tr>"
strwrite += "<tr><td valign=top>thisPLoc: </td><td>[" + thisPLoc + "]</td></tr>"
strwrite += "<tr><td valign=top>thisTHost: </td><td>[" + thisTHost + "]</td></tr>"
strwrite += "<tr><td valign=top>thisHost: </td><td>[" + thisHost + "]</td></tr>"
document.write( strwrite );
</script>
thisTLoc = top.location.href; <BR>
thisPLoc = parent.document.location; <BR>
thisTHost = top.location.hostname; <BR>
thisHost = location.hostname;<BR>
<script language="javascript">
tmpHPage = thisHREF.split( "/" );
thisHPage = tmpHPage[ tmpHPage.length-1 ];
tmpUPage = thisURL.split( "/" );
thisUPage = tmpUPage[ tmpUPage.length-1 ];
strwrite = "<tr><td valign=top>thisHPage: </td><td>[" + thisHPage + "]</td></tr>"
strwrite += "<tr><td valign=top>thisUPage: </td><td>[" + thisUPage + "]</td></tr>"
document.write( strwrite );
</script><tr><td>
|
顺便把js获取当前url的方法也说一下,获取当前页面的url,包括协议、域名、文件夹、文件名和完整的查询参数。
window.location.href
解决IE和FF获取Referer在IE中用javascript做跳转,比如用window.location.href = “”; google如果使用document.referrer无法取到浏览器请求的HTTP referrer,因为IE清空了
而其他主流浏览器Firefox和Chrome都会保留referrer,没办法,这意味着IE又要享受“部长级”特殊待遇了:
以下代码可以解决ie的这个问题:
代码如下 |
复制代码 |
//检测如果是ie浏览器,则手动的给增加一个referer
if (/MSIE (d+.d+);/.test(navigator.userAgent)){
var referLink = document.createElement('a');
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
} else {
location.href = url;
}
|
这样的原理就是给IE浏览器的页面偷偷加了个链接,然后自动点这个链接,于是referrer就能保留了 |