如何创建一个“;“桌面版”;移动网站上的链接,而不重定向到移动网站

How to create a "Desktop Version" link on mobile website without it redirecting to the mobile site

本文关键字:网站 移动网 移动 重定向 链接 创建 何创建 一个 桌面版 桌面      更新时间:2023-09-26

所以,我以前见过这个问题,但没有真正的答案(除非我错过了它)。

我正在使用此重定向到site.com 上的移动网站

      if (screen.width <= 800) {
      window.location = "/m";
      }

和简单的HTML重定向到m.site.com 上的桌面版本

     <a href="../"> Desktop Version </a>

当然,由于上面的if语句,它会重定向到移动版本。

如何通过使用javascript来解决此问题?

谢谢。

本地存储受到广泛支持,所以让我们使用它。无需使用cookie。

如果我们这样做,点击移动网站上显示的"桌面版"链接:

localStorage.setItem("forceToDesktop", "true")
// Followed by redirect to desktop with JS

我们修改了屏幕宽度检查,以包括对上述值的检查:

if (localStorage.forceToDesktop !== "true" && screen.width <= 800) {
    // Do redirect stuff
}

如果forceToDesktop值未设置,并且屏幕宽度小于或等于800,这将显示移动站点。

然而,这个谜题仍然缺少一部分。移动用户在选择只查看桌面网站后,如何返回移动网站?

我们需要以某种方式删除forceToDesktop值。我会做这样的事。

if (localStorage.forceToDesktop === "true" && screen.width <= 800) {
    // Add a link to the page called something like "view mobile site",
    // and have it run the below javascript function on click
    var backToMobile = function () {
        localStorage.removeItem("forceToDesktop");
        // Redirect back to the mobile version of the page, 
        // or just redirect back to this page, and let the normal 
        // mobile redirect do its thing.
    }
}