JS实现外链无法访问,document.referrer方法

本文介绍了一种通过JavaScript检查document.referrer来防止B页面被非A平台链接直接打开的方法,当referrer为空时,针对不同浏览器版本采取不同的策略,确保页面仅接受来自A平台的合法链接。

需求:有个A平台点击需要跳转到新的页面B,但是这个B页面只允许从A平台点击的时候通过链接打开,如果是浏览器输入或者复制都不允许打开,这种做法是为了防止外链暴露

思路:可以使用document.referrer方法,这个方法会返回一个值,如果用户直接导航到页面(不是通过链接,而是通过使用书签),则该值为空字符串。由于此属性仅返回一个字符串,因此它不会授予对引用页的文档对象模型 (DOM) 访问权限。

代码如下:

   const type = document.referrer
          console.log(type, 'type')

由于我是直接通过输入网址打开的所以type为空,如果是通过点击链接打开的会返回当前页面的地址,通过判断type是不是为空就可以实现关闭外链

关闭外链的代码:

       if (type == "" ){
            alert('请求地址无效')
            if (navigator.userAgent.indexOf('MSIE') > 0) {
              if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
                window.opener = null
                window.close()
              } else {
                window.open('', '_top')
                window.top.close()
              }
            } else if (navigator.userAgent.indexOf('Firefox') > 0) {
              window.location.href = 'about:blank'
            } else {
              window.opener = null
              window.open('about:blank', '_self')
              window.close()
            }
          }

全部代码如下:

    created() {
          const type = document.referrer
          if (type == "" ){
            alert('请求地址无效')
            if (navigator.userAgent.indexOf('MSIE') > 0) {
              if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
                window.opener = null
                window.close()
              } else {
                window.open('', '_top')
                window.top.close()
              }
            } else if (navigator.userAgent.indexOf('Firefox') > 0) {
              window.location.href = 'about:blank'
            } else {
              window.opener = null
              window.open('about:blank', '_self')
              window.close()
            }
          }
        },

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值