首页 > 解决方案 > 如何在变量中捕获引用 URL,然后重定向到新页面 jquery 或 javascript

问题描述

几乎拥有它,但可能需要帮助:

我创建了一个脚本来重定向并设置一个来自我们网站的任何页面的 cookie。因此,即使用户是从新闻文章的直接链接进来的,它也会将他们重定向到我们的“splash”页面并设置一个“cookie”以避免进一步的重定向。我的那部分工作完美。

$(document).ready(function() {
  if (typeof Cookies.get('secondvisit') === 'undefined') {
    window.location.href = "/index-donate.php";
  }
})

但是,我们现在想要捕获他们首先访问的 URL 并创建一个变量,以便我们可以在他们阅读我们的 SPLASH 页面后将它们链接回该页面。

所以在上面的例子中:

通过直接链接进入:/news/article1.php 没有检测到 cookie,所以我们首先需要“捕获”他们在“$page-refer”中进入的页面,然后将它们重定向到我们的 Splash 页面。

然后,在启动页面上,我们会向他们提供一个链接,其中包含“继续访问网页”和“$page-refer”链接。

我确实尝试过这个(下图),但这只是抓取“谷歌”页面,而不是他们首先点击的我们的网页。

谢谢!

$(document).ready(function() {
  if (typeof Cookies.get('secondvisit') === 'undefined') {
    var referringURL = document.referrer;
    var local = referringURL.substring(referringURL.indexOf("?"), referringURL.length);
    location.href = "/index-donate.php" + local;
  }
})

标签: javascriptjqueryredirect

解决方案


我认为您可以在进行重定向时将 URL 添加为 cookie,例如:

$(document).ready(function () {
  if (typeof Cookies.get('secondvisit') === 'undefined') {
    Cookies.set('initialvisitedpage', window.location.href);
    window.location.href = "/index-donate.php";
  }
});

然后你可以将它们重定向到 cookie 值:

$(document).ready(function() {
  if (typeof Cookies.get('secondvisit') === 'undefined') {
    window.location.href = Cookies.get('initialvisitedpage') || '/'; // or whatever this could default to in case they don't have the cookie
  }
})

推荐阅读