jai gupta
jai gupta

Reputation: 99

In Salesforce Lightning Web Component, How can I find if I am using Salesforce Mobile App OR Mobile browser

We can get the device size and the type by using LWC's '@salesforce/client/formFactor' module. But how can I get if I am working on Mobile App or mobile Browser in LWC.

I believe the above module will always give form factor SMALL as both are in mobile device so is there any other module OR any JS way to find if I am working on Mobile APP or Mobile Browser.

Upvotes: 3

Views: 2857

Answers (1)

jai gupta
jai gupta

Reputation: 99

After some research, found that "@salesforce/client/formFactor" module will return Large even if the page is opened in Mobile Browser. In case of Mobile app FORM_FACTOR will be "small" which can be used to identify if this is Mobile Browser OR mobile App.

import { LightningElement } from 'lwc';
import FORM_FACTOR from '@salesforce/client/formFactor';

export default class DeviceSelection extends LightningElement {
    largeSlotChangeHandler() {
        const largeDiv = this.template.querySelector('.largeDevice');
        FORM_FACTOR.toLowerCase() === 'large' ? largeDiv.classList.remove('slds-hide'): '' ;
    }

    mediumSlotChangeHandler() {
        const mediumDiv = this.template.querySelector('.mediumDevice');
        FORM_FACTOR.toLowerCase() === 'medium' ? mediumDiv.classList.remove('slds-hide'): '' ;
    }

    smallSlotChangeHandler() {
        const smallDiv = this.template.querySelector('.smallDevice');
        FORM_FACTOR.toLowerCase() === 'small' ? smallDiv.classList.remove('slds-hide'): '' ;
    }   
}

The HTML file can be

<template>
    <div class="largeDevice slds-hide">
        <slot name="large" onslotchange={largeSlotChangeHandler}></slot>
    </div>
    <div class="mediumDevice slds-hide">
        <slot name="medium" onslotchange={mediumSlotChangeHandler}></slot>
    </div>
    <div class="smallDevice slds-hide">
        <slot name="small" onslotchange={smallSlotChangeHandler}></slot>
    </div>
</template>

And then this can be used conditionally for different devices:

<c-device-selection>
    <div slot="large">
        Show this message for only large device.
    </div>
    <div slot="medium">
        Show this message for only medium devices.
    </div>
    <div slot="small">
        Show this message for only small devices.
    </div>
</c-device-selection>  

Upvotes: 2

Related Questions