【问题标题】:How to capture the referring URL in a variable and then redirect to new page jquery or javascript如何在变量中捕获引用 URL,然后重定向到新页面 jquery 或 javascript
【发布时间】:2021-11-10 17:33:55
【问题描述】:

差不多有,但可能需要帮助:

我创建了一个脚本来重定向并设置来自我们网站任何页面的 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”链接的“继续访问网页”链接。

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

谢谢!

$(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;
  }
})

【问题讨论】:

  • 您不需要引荐来源网址,您需要当前页面的 url,因为 javascript 正在该页面上执行。 window.location.href 是您正在寻找的。 location.href = "/index-donate.php?page-refer=" + encodeURIComponent(location.href)
  • 这个工作完美。谢谢你!
  • 很高兴听到这个消息。请记住,您可以随时自行回答您的问题stackoverflow.com/help/self-answer 发布更新的代码
  • 知道了!非常感谢!

标签: javascript jquery redirect


【解决方案1】:

我认为您可以在进行重定向时将 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
  }
})

【讨论】:

  • 感谢您的回复。我使用了上面的另一个建议。我很欣赏代码。
【解决方案2】:

把一个很好的答案放在一起,感谢cmets和push:

页脚脚本模板:

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

然后在我的启动页面上:

我捕获了变量$pageredirect via $_GET['page-refer'],然后将其作为页面下方的链接呈现(如果已设置)!

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多