Home > Blockchain >  How to detect mobile or desktop and not get cheated by chrome dev tools
How to detect mobile or desktop and not get cheated by chrome dev tools

Time:06-19

I'm trying to detect when the user uses a mobile device on my application.

Usually, we will detect by using a user-agent or touchable screen, but chrome mobile mode in the dev tools changes both of those.

Do you have any idea how can i detect mobile or desktop and not get cheated by chrome dev tools?

CodePudding user response:

Instead of going for type of device, you can check for operating system. Here is a list of possible values you can use.

windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];
android = "Android";
typeOfOS = window.navigator.platform;

if (windowsPlatforms.includes(typeOfOS)) {
     //do for windows
} else if(typeOfOS === android){
     //do for android
}

CodePudding user response:

You can do it in css. You can use the @media to see if the screen size is smaller than that usually desktops have and by this you will be able to make your application responsive. Take a look at this code:

body {
    --background-image: url('https://thumbs.dreamstime.com/b/vertical-banner-template-hands-typing-computer-office-supplies-distance-education-e-learning-obtaining-university-156390588.jpg');
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    background-image: var(--background-image);
    background-size: 100vw 100vh;
    z-index: -1000;
}
#submit-form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    height: 180px;
    width: 300px;
    background-color: white;
    border-radius: 10px;
    border: 2px dashed;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    z-index: 1000;
}
#email-input {
    height: 30px;
    width: 220px;
    border-radius: 10px;
}
#submit-button {
    height: 30px;
    width: 80px;
    border-radius: 10px;
    background-color: lightgreen;
    border: 1px dashed;
}

@media all and (min-width: 1000px) {
   body {
    background-image: url('https://img.freepik.com/free-vector/online-education-students-view-lessons-through-mobile-devices-during-distance-learning_178888-361.jpg?w=2000');
   }
   #submit-form {
    height: 250px;
    width: 500px;
   }
   #email-input {
    height: 50px;
    width: 300px;
    border-radius: 10px;
}
}

Here I am styling the sites for mobile devices first, and then, I am checking if the user is on a desktop and if he is, I am making the website responsive again.

This was for the styling part, but, what if you want to detect it in JavaScript?

You can use a simple function for this:

function findUserDevice() {
  const isOnMobile = false;

  if(window.innerWidth < window.innerHeight) {
    isOnMobile = true;
  }
  return isOnMobile;
}

This is what I usually use, hope this was helpful!

  • Related