模仿Gitee实现站外链接跳转时进行确认

概述

如Gitee等网站,在有外部链接的时候如果不是同域则会出现一个确认页面。本文就带你看看这个功能应该如何实现。

效果

实现

1. 实现思路

将打开链接作为参数传递给一个中间页面,在页面加载的时候判断链接的域名和当前网站是否同域,同域则直接跳转,如果不同域,则展示确认页面进行在此确认。如下为跳转页面。

复制代码
http://localhost:3001/#/link?target=https://www.baidu.com

2. 实现代码

vue 复制代码
<template>
    <div class="layout-main">
      <div class="layout-box">
        <p>即将跳转到外部网站</p>
        <p>您将要访问的链接不属于{{ local }},请关注您的账号安全。</p>
        <p>{{ target }}</p>
        <p>
          <el-button type="warning" @click="goto">继续前往</el-button>
        </p>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    computed: {
      isSameDomain() {
        const host = this.local
        const targetHost = new URL(this.target).host
        return host === targetHost
      },
      target() {
        return this.$route.query.target
      },
      local() {
        return window.location.host
      }
    },
    created() {
      if(this.isSameDomain) window.location.href = this.target
    },
    methods: {
      goto() {
        window.location.href = this.target
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  $size: 38rem;
  
  .layout-main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
    font-size: 1.2rem;
    background: #efefef;
    padding: 0 calc(50% - $size / 2);
    h3 {
      width: $size;
      text-align: center;
      font-size: 1.8rem;
      margin: 0.5rem 0;
    }
    .layout-box {
      background-color: #ffffff;
      width: $size;
      border-radius: 0.4rem;
      box-shadow: 0.1rem 0.1rem 0.4rem #ccc;
      padding: 1.5rem;
      p {
        margin: 0;
        line-height:2;
        &:first-child {
          font-size: 1.5rem;
          margin-bottom: 1rem;
          line-height: 1;
        }
        &:last-child {
          text-align: right;
        }
      }
    }
  }
  </style>
``
相关推荐
艾小码5 分钟前
还在手动处理页面跳转?掌握Vue Router 4,你的导航效率翻倍!
前端·javascript·vue-router
xxy-mm6 小时前
Javascript 中的继承
开发语言·javascript·ecmascript
锋行天下8 小时前
公司内网部署大模型的探索之路
前端·人工智能·后端
1024肥宅8 小时前
手写 EventEmitter:深入理解发布订阅模式
前端·javascript·eventbus
海市公约10 小时前
HTML网页开发从入门到精通:从标签到表单的完整指南
前端·ide·vscode·程序人生·架构·前端框架·html
3秒一个大10 小时前
HTML5 与 JavaScript 中的二进制数据处理:ArrayBuffer 与 TextEncoder/Decoder 实践
javascript
purpleseashell_Lili10 小时前
如何学习 AG-UI 和 CopilotKit
javascript·typescript·react
行云流水62610 小时前
前端树形结构实现勾选,半勾选,取消勾选。
前端·算法
diudiu_3310 小时前
web漏洞--认证缺陷
java·前端·网络
阿珊和她的猫11 小时前
<video>` 和 `<audio>` 标签的常用属性解析
前端