Kitty
Kitty

Reputation: 167

How to detect whether salesforce lightning app is running on a mobile browser or desktop browser?

We have salesforce lightning app which runs on both mobile and desktop. Need to write some code only for mobile application. How to detect whether app is running on a mobile browser or desktop browser? I used following code but its not working:

checkMobileBrowser: function(component){
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
        return true;        
    }else{
        return false;
    }
}

Upvotes: 3

Views: 6109

Answers (3)

Daisy Scott
Daisy Scott

Reputation: 31

The $Browser global value provider returns information about the hardware and operating system of the browser accessing the application.

Returns a FormFactor enum value based on the type of hardware the browser is running on.

DESKTOP for a desktop client PHONE for a phone including a mobile phone with a browser and a smartphone TABLET for a tablet client (for which isTablet returns true)

Ctrl

({
    checkBrowser: function(component) {
        var device = $A.get("$Browser.formFactor");
        alert("You are using a " + device);
    }
})
Component

<aura:component>
        {!$Browser.isTablet}
        {!$Browser.isPhone}
        {!$Browser.isAndroid}
        {!$Browser.formFactor}
    </aura:component>

By using this way you can determine

Resource: http://www.janbask.com/salesforce-lightning

Upvotes: 3

Hleb
Hleb

Reputation: 7371

you can write JavaScript function for validation of browser's user agent:

function detectmob(){ 
    if(navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)){
        return true;
    }else{
        return false;
    }
}

Upvotes: 0

JF Paradis
JF Paradis

Reputation: 121

You can also use the $Browser global value provider:

function checkMobileBrowser(){ 
   return $A.get("$Browser.formFactor") !== "DESKTOP"
}

This will ensure that your detection matches what the application uses, if your component is ever embedded in S1 or SFX, and everything will switch on the same logic.

$Browser is also available in component markup:

<aura:if "{!$Browser.formFactor !== 'DESKTOP'}">
   <component/>
</aura:if> 

You might want to search the documentation for $Browser, because it allows for very granular hardware detection, and there might be something else for your specific use case.

https://resources.docs.salesforce.com/sfdc/pdf/lightning.pdf

Upvotes: 2

Related Questions