【问题标题】:How to link source of traffic with JS function如何将流量来源与 JS 函数联系起来
【发布时间】:2022-01-01 05:35:43
【问题描述】:

现在请我使用这个 Javascript 函数

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(";").shift();
}

function setLastAccess() {
  const date = new Date();
  const expireMs = 0.5 * 60 * 1000; // number of minutes
  date.setTime(date.getTime() + expireMs);
  document.cookie = `lastAccess=${new Date().getTime()};expires=${date.toUTCString()};path=/`;
}

if (!getCookie('lastAccess')) {
  window.location.href = "http://google.com";
  setLastAccess(); // set your last access at the end
} else {
  setTimeout(function() {
    document.getElementById('button-login').click();
  }, 1000);
}

但是如果网站流量不是来自 Google chrome 或 Firefox 浏览器,我现在想让这个功能不起作用。如何做到这一点? 如果流量来自任何其他浏览器,只需给用户一条消息。

【问题讨论】:

    标签: javascript google-chrome cookies session-cookies


    【解决方案1】:

    你可以看看user agents,但它是not recommended to serve different content to different browsers,虽然在你的情况下它只是一个函数,所以它可能没问题。如果你真的想检查 Chrome 或 Firefox,你可以这样做:

    if (/chrome|firefox/gi.test(window.navigator.userAgent)) {
      // chrome or firefox
    } else {
      alert("not using chrome or firefox")
    }
    

    【讨论】:

    • 感谢您的回答,但是当我运行它时 if (/chrome|firefox/gi.test(window.navigator.userAgent)) { window.location.href = "google.com"; } else { alert("不使用 chrome 或 firefox") }
    • 即使我从 Microsoft Edge 运行它也会重定向用户
    • 您好亲,感谢您的帮助,当我删除“gi”并将 ) 添加到代码时它起作用了。
    • 但现在即使我使用谷歌浏览器也会发出警报。
    • 您至少需要正则表达式上的i 标志以使其不区分大小写。看起来大多数用户代理中都有“chrome”这个词。试试这个例子developer.mozilla.org/en-US/docs/Web/API/Window/navigator
    猜你喜欢
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多