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

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 2, 2025

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

      June 2, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 2, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 2, 2025

      How Red Hat just quietly, radically transformed enterprise server Linux

      June 2, 2025

      OpenAI wants ChatGPT to be your ‘super assistant’ – what that means

      June 2, 2025

      The best Linux VPNs of 2025: Expert tested and reviewed

      June 2, 2025

      One of my favorite gaming PCs is 60% off right now

      June 2, 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

      `document.currentScript` is more useful than I thought.

      June 2, 2025
      Recent

      `document.currentScript` is more useful than I thought.

      June 2, 2025

      Adobe Sensei and GenAI in Practice for Enterprise CMS

      June 2, 2025

      Over The Air Updates for React Native Apps

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

      You can now open ChatGPT on Windows 11 with Win+C (if you change the Settings)

      June 2, 2025
      Recent

      You can now open ChatGPT on Windows 11 with Win+C (if you change the Settings)

      June 2, 2025

      Microsoft says Copilot can use location to change Outlook’s UI on Android

      June 2, 2025

      TempoMail — Command Line Temporary Email in Linux

      June 2, 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

    Development

    A Beginner’s Guide to Graphs — From Google Maps to Chessboards

    June 2, 2025
    Development

    How to Code Linked Lists with TypeScript: A Handbook for Developers

    June 2, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Microsoft Confirms CrowdStrike Outage Root Cause, Outlines Plans to Improve Reliability

    Development

    Operation Pandora Takes Down a Dozen Fraudulent Call Centers

    Development

    Working with Laravel’s Uri Class for Enhanced URL Manipulation

    Development

    U.S. Customs and Border Protection Issues Guide for Travelers on Facial Recognition Opt-Out

    Development

    Highlights

    The upcoming Ray-Ban Meta smart glasses may feature the display upgrade we’ve been hoping for

    December 23, 2024

    The upcoming Ray-Ban smart glasses will reportedly feature similar ‘in-lens’ displays as Meta’s Orion prototype…

    North Korea falls off the internet – is the United States to blame?

    April 9, 2025

    FSB Uses Trojan App to Monitor Russian Programmer Accused of Supporting Ukraine

    December 7, 2024

    Void Linux Sorprende: Xfce 4.20 Disponibile in Tempi Record!

    December 20, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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