Magento, Magento 2

How to Detect Mobile Device in Magento 2

How to Detect Mobile Device in Magento 2

In this tutorial, Today I will explain to how to detect mobile device programmatically in Magento 2. In Magento 2, When we design or develop anything at that time, we need to do different functionality for mobile device and desktop device. At that time, how can we detect mobile device when page load?

Let’s follow the below code to detect mobile device :

You may also like this :

I created Index.php controller for that at app/code/RH/Helloworld/Controller/Index/ and add this below code :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action {

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Framework\HTTP\Header
     */
    protected $httpHeader;

    /**
     * @param \Magento\Framework\App\Action\Context      $context
     * @param \Magento\Framework\HTTP\Header             $httpHeader
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\HTTP\Header $httpHeader,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->httpHeader = $httpHeader;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    /**
     * Detect Mobile view or Desktop View
     *
     * @return void
     */
    public function execute() {
        $resultPage = $this->resultPageFactory->create();
        $userAgent = $this->httpHeader->getHttpUserAgent();
        $isMobile = \Zend_Http_UserAgent_Mobile::match($userAgent, $_SERVER);
        if ($isMobile) {
            $resultPage->getConfig()->getTitle()->prepend(__("Mobile View")); // Mobile view logic add here
        } else {
            $resultPage->getConfig()->getTitle()->prepend(__("Desktop View")); // Desktop view logic add here
        }
        return $resultPage;
    }

}

You can add this above code in your controller or any file. You need to inject \Magento\Framework\HTTP\Header class into your construct.

In above code, if condition is true then, it’s mobile device otherwise, it will be desktop device. If you want to add code logic for mobile view then, you need to add inside if condition. For desktop view, you need to add code inside else condition.

That’s it !!!

I hope this blog is easy to understand about how to detect mobile device programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,