How to detect for Mobile device in Magento 2?

In Magento 2, We can check user requests coming from web or mobile.

In some situations, we need to show/hide different data/blocks on mobile devices. At that time we can use the code snippet below to check user requests from mobile or web.

Let’s create a block class and look at how to detect Mobile devices.


namespace Mageclues\DeviceDetect\Block;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Element\Template;
use Magento\Framework\HTTP\Header;

class Demo extends Template
    protected $_httpHeader;

    public function __construct(
        Context $context,
        Header $httpHeader,
        array $data = []
        $this->_httpHeader = $httpHeader;
        parent::__construct($context, $data);

    public function isMobileDevice()
        $reqUserAgent =  $this->_httpHeader->getHttpUserAgent();
        $isRequestFromMobile = \Zend_Http_UserAgent_Mobile::match($reqUserAgent, $_SERVER);

        if($isRequestFromMobile) {
           return true;
        return false;

We have used magento core class \Magento\Framework\HTTP\Header to get header UserAgent.

You can call isMobileDevice() block function from your template file.

We hope this blog is useful for you, please leave comment if you have any question.

thank you!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *