Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 1, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 1, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 1, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 1, 2025

      7 MagSafe accessories that I recommend every iPhone user should have

      June 1, 2025

      I replaced my Kindle with an iPad Mini as my ebook reader – 8 reasons why I don’t regret it

      June 1, 2025

      Windows 11 version 25H2: Everything you need to know about Microsoft’s next OS release

      May 31, 2025

      Elden Ring Nightreign already has a duos Seamless Co-op mod from the creator of the beloved original, and it’ll be “expanded on in the future”

      May 31, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Student Record Android App using SQLite

      June 1, 2025
      Recent

      Student Record Android App using SQLite

      June 1, 2025

      When Array uses less memory than Uint8Array (in V8)

      June 1, 2025

      Laravel 12 Starter Kits: Definite Guide Which to Choose

      June 1, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Photobooth is photobooth software for the Raspberry Pi and PC

      June 1, 2025
      Recent

      Photobooth is photobooth software for the Raspberry Pi and PC

      June 1, 2025

      Le notizie minori del mondo GNU/Linux e dintorni della settimana nr 22/2025

      June 1, 2025

      Rilasciata PorteuX 2.1: Novità e Approfondimenti sulla Distribuzione GNU/Linux Portatile Basata su Slackware

      June 1, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Methods for identifying desktop, mobile, or tablet device in the LWC component

    Methods for identifying desktop, mobile, or tablet device in the LWC component

    January 17, 2025

    In order to write device-specific code in Salesforce LWC (Lightning web components), we will explore different methods of detecting a device in this blog. The following methods can be used in Lightning Web Components (LWC) to identify a device or distinguish between a desktop, tablet, or mobile device:

    Pexels Pixabay 4158

    1. Using Standard web APIs navigator.userAgent

    In Lightning Web Components (LWC), device detection is implemented using standard web APIs like navigator.userAgent, allowing developers to identify device types (e.g., phone, tablet, desktop) and operating systems by analyzing the user agent string. This approach provides flexibility and supports modern web standards.

    Example:

    import { LightningElement } from 'lwc';
    
    export default class DetectDevice extends LightningElement {
        isPhone = false;
        isTablet = false;
        isAndroid = false;
        formFactor = 'Unknown';
    
        connectedCallback() {
            this.detectDevice();
        }
    
        detectDevice() {
            const userAgent = navigator.userAgent || navigator.vendor || window.opera;
            // Detect Android
            this.isAndroid = /android/i.test(userAgent);
            // Detect iOS
            const isIOS = /iPad|iPhone|iPod/.test(userAgent) && !window.MSStream;
            // Detect Tablets
            const isTablet = /Tablet|iPad/.test(userAgent);
            // Detect Phones
            const isPhone = /Mobile|iPhone|Android/.test(userAgent) && !isTablet;
            // Assign properties
            this.isPhone = isPhone;
            this.isTablet = isTablet || isIOS;
            this.formFactor = isPhone ? 'Phone' : isTablet ? 'Tablet' : 'Desktop';
        }
    }
    

    2. Use CSS Media Queries

    In both Lightning Web Components (LWC) and Aura Components, detecting the device form factor using CSS Media Queries is a robust and declarative approach. Media queries enable developers to define styles that apply conditionally based on the device’s screen size, resolution, orientation, or other media features, without relying on JavaScript or Salesforce-specific utilities like $Browser. We can use CSS media queries to detect the device type or screen size and apply styles or classes accordingly.

    Detecting Devices Using CSS Media Queries

    You can define breakpoints to target specific devices like phones, tablets, or desktops. For example:

    • Phones: Devices with a screen width up to 767px.
    • Tablets: Devices with a screen width between 768pixel and 1024pixel.
    • Desktops: Devices with a screen width above 1024px.

    For Example

    • HTML Template:
    html
    <template>
      <div class={deviceClass}>
        Content here
      </div>
    </template>
    
    • CSS:
    @media (max-width: 768px) {
      .mobile {
        display: block;
      }
    }
    @media (min-width: 769px) {
      .desktop {
        display: block;
      }
    }
    
    • JavaScript:
    import { LightningElement } from 'lwc';
    
    export default class DetectDeviceLwc extends LightningElement {
      get deviceClass() {
        return window.innerWidth <= 768 ? 'mobile' : 'desktop';
      }
    }
    

    Example: 2

    In the .css file of the LWC component

    /* For Phones */

    @media screen and (max-width: 767px) {
        .example {
            font-size: 14px;
            color: blue;
        }
    }
    
    

    /* For Tablets */

    @media screen and (min-width: 768px) and (max-width: 1024px) {
        .example {
            font-size: 16px;
            color: green;
        }
    }
    

    /*For Desktops */

    @media screen and (min-width: 1025px) {
        .example {
            font-size: 18px;
            color: black;
        }
    }
    

    3. Check Screen Size with window.innerWidth or window.matchMedia

    We can dynamically check screen width or use the matchMedia API to determine the device type.

    window.innerWidth: Simpler and more straightforward, but can be less performant for frequent resize events.

    window.matchMedia: More powerful and efficient, especially when dealing with complex media queries or when you only need to respond to specific media query changes.

    Example:

    import { LightningElement } from 'lwc';
    
    export default class DetectDeviceLwc extends LightningElement {
      isMobile = false;
    
      connectedCallback() {
        this.checkDevice();
        window.addEventListener('resize', this.checkDevice.bind(this));
      }
    
      disconnectedCallback() {
        window.removeEventListener('resize', this.checkDevice.bind(this));
      }
    
      checkDevice() {
        this.isMobile = window.innerWidth <= 768; // Define your breakpoint here
      }
    }
    
    function checkScreenWidth() {
      const smallScreenQuery = window.matchMedia("(max-width: 767px)");
      const mediumScreenQuery = window.matchMedia("(min-width: 768px) and (max-width: 1023px)");
    
      if (smallScreenQuery.matches) {
        console.log("Small screen");
      } else if (mediumScreenQuery.matches) {
        console.log("Medium screen");
      } else {
        console.log("Large screen");
      }
    }
    
    // Call the function on page load
    checkScreenWidth();
    
    // Add listeners for media query changes
    smallScreenQuery.addEventListener("change", checkScreenWidth);
    mediumScreenQuery.addEventListener("change", checkScreenWidth);
    

    4. Leverage Platform-Specific Styles in Salesforce

    If your application runs in Salesforce Mobile App, you can use specific SLDS classes for responsiveness.

    • For example, use the slds-size_1-of-1, slds-medium-size_1-of-2, or slds-large-size_1-of-3 classes to control layout depending on the screen size.

    In Lightning Web Components (LWC), leveraging platform-specific styles in Salesforce is an effective approach to detect and adapt to devices, ensuring a seamless user experience. Salesforce provides a unified and responsive design system through the Lightning Design System (SLDS), which includes platform-specific utility classes and design tokens. These tools allow developers to tailor component styling and behavior for different devices and screen sizes without relying heavily on custom CSS or JavaScript.

    5. Lightning Platform Features

    Use Salesforce’s User-Agent and Platform context for mobile/desktop detection:

    • In Visualforce or Aura, we can use $UserContext.uiTheme or $UserContext.uiThemeDisplayed.
    • In LWC, this can be combined with server-side logic or custom platform detection flags passed from Apex or configuration.

    Custom Apex Logic

    If needed, pass device information from Apex to the LWC by using a custom setting or logic to detect if the user is accessing Salesforce from a mobile app or desktop browser.

    UserInfo.getUiThemeDisplayed(); // Returns ‘Theme4d’ for Desktop, ‘Theme4t’ for Mobile

    @AuraEnabled
    public static Boolean isMobile() {     
    return UserInfo.getUiThemeDisplayed() == 'Theme4t';
    }
    

    You can then consume this information in your LWC via an imperative Apex call.

    6. Salesforce Mobile SDK (If Applicable)

    For apps integrated with the Salesforce Mobile SDK, you can directly use the SDK’s methods to detect the environment and pass the device type to your LWC.

    Conclusion:

    By combining one or more of these methods allows for more reliable device detection, enabling you to implement device-specific code tailored to your application. These approaches are particularly valuable for ensuring your LWC components accurately identify and respond to the appropriate device.

     

    References:

    Apex Reference Guide

    View Devices with mobile device tracking 

    You Can Also Read:

    1. A Complete Guide to Navigation Service in Lightning Web Components: Part 1
    2. A Complete Guide to Navigation Service in Lightning Web Components: Part 2

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleSecurely Interacting with AWS Services Using Boto3 API
    Next Article Integrating SCSS with JavaScript

    Related Posts

    Artificial Intelligence

    Markus Buehler receives 2025 Washington Award

    June 1, 2025
    Artificial Intelligence

    LWiAI Podcast #201 – GPT 4.5, Sonnet 3.7, Grok 3, Phi 4

    June 1, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Massive Data Breach in Tamil Nadu: 600,000 Migrant Workers’ Data Allegedly Leaked on Dark Web

    Development

    How to Increase PC Speed

    Web Development

    CVE-2025-5129 – Sangfor aTrust Directory Traversal Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2024-13957 – ASPECT SSRF Server Side Request Forgery

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    iOS 18 makes this once complicated iPhone feature much more user-friendly (and I’m a fan)

    June 11, 2024

    At WWDC 2024, Apple unveiled updated widgets, multiple shortcut pages, and a slick new way…

    Ghostty DEB Installers Now Available for Ubuntu 25.04

    April 21, 2025

    CVE-2025-2156 – Red Hat Linux Kernel Uninitialized Memory Access

    April 30, 2025

    Discover 700+ free resources and tools

    June 4, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.