简体   繁体   中英

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

So, I have seen this asked before but with no real answer (unless I am missing it).

I am using this to redirect to the mobile site on site.com

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

And simple HTML to redirect to desktop version on m.site.com

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

but of course, it redirects to the mobile version due to the if statement above.

How can I remedy this with the use of javascript?

Thank you.

Local storage is widely supported, so let's use it. No need to bother with cookies.

If we do something like this on click for the "Desktop Version" link that is shown on the mobile site:

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

And we modify our screen width check to include a check for the above value:

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

This will show the mobile site if the forceToDesktop value has not been set, and if the screen width is less than or equal to 800.

However, there is still one part of the puzzle missing. How does a mobile user get back to the mobile site, after choosing to see the desktop site only?

We need to remove the forceToDesktop value somehow. I would do something like this.

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM