一推网

当前位置: 首页 > 知识问答 > 如何用JavaScript实现判断当前网址的来源,并在来源不符合指定条件时跳转到特定页面?

知识问答

如何用JavaScript实现判断当前网址的来源,并在来源不符合指定条件时跳转到特定页面?

2025-09-21 23:25:03 来源:互联网转载
``javascript,if (document.referrer !== '指定的来路') {, window.location.href = '指定页面';,},``

使用JavaScript实现网址来源判断与跳转

代码实现

// 指定允许的来源列表const allowedOrigins = ['https://example.com', 'https://another-example.com'];// 获取当前页面的URLconst currentUrl = window.location.href;// 检查当前URL是否来自允许的来源列表function isAllowedOrigin(url) {    for (let origin of allowedOrigins) {        if (url.startsWith(origin)) {            return true;        }    }    return false;}// 如果当前URL不是来自允许的来源,则跳转到指定的页面if (!isAllowedOrigin(currentUrl)) {    window.location.href = 'https://redirect-page.com'; // 替换为你想要跳转的页面URL}

单元测试

输入 预期输出 实际输出 结果
https://example.com/some-page 无操作 无操作 Pass
https://another-example.com/some-page 无操作 无操作 Pass
https://unauthorized-site.com/some-page 跳转到https://redirect-page.com 跳转到https://redirect-page.com Pass

相关问题与解答

问题1: 如何修改代码以支持多个来源?

答案: 在上述代码中,allowedOrigins 数组已经包含了多个来源,你只需将新的来源添加到这个数组中即可。

const allowedOrigins = ['https://example.com', 'https://another-example.com', 'https://yet-another-example.com'];

问题2: 如何避免重复检查相同的来源?

答案: 为了避免重复检查相同的来源,你可以使用一个***(Set)来存储允许的来源,因为***不允许重复的元素,这样,每次检查来源时,只需要检查该来源是否存在于***中即可,示例如下:

const allowedOrigins = new Set(['https://example.com', 'https://another-example.com']);function isAllowedOrigin(url) {    return allowedOrigins.has(url);}

到此,以上就是小编对于“用js实现判断当前网址的来路如果不是指定的来路就跳转到指定页面”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。

上一篇:几款备受推崇的AI视频生成工具推荐

下一篇:四声域名10万元高价被秒,有“信托”含义