Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5557

Detect your device is Mobile or Desktop in Magento 2

$
0
0

Hello Friends!

In this blog, we will learn how we can detect our device in Magento 2 programmatically.

In Magento 2, if you want to display different content or layout on a page according to Desktop or Mobile, then you use the following code in your code.

1. To Detect Desktop Device:

$userAgent = $this->getRequest()->getHeader('useragent');
$server    = $this->getRequest()->getServer();
        
$isDesktopDevice = \Zend_Http_UserAgent_Desktop::match($userAgent, $server);
if ($isDesktopDevice) {
   //Write your code here for Desktop view
}

2. To Detect Mobile Device:

$userAgent = $this->getRequest()->getHeader('useragent');
$server    = $this->getRequest()->getServer();

$isMobileDevice = \Zend_Http_UserAgent_Mobile::match($userAgent, $server);
if ($isMobileDevice) {
   //Write your code here for Mobile view
}

Here, check the complete code in a controller file.

<?php
/**
 * Vendor's Short Description
 *
 * @category  Vendor
 * @package   Vendor_CustomModule
 * @author    Vendor
 * @copyright Copyright (c) Vendor
 * @license   https://example.com/license.html
 */
namespace Vendor\CustomModule\Controller\Demo;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class CheckDevice extends Action
{
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;

    /**
     * initialization
     *
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    
    /**
     * Execute method
     */
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        $userAgent  = $this->getRequest()->getHeader('useragent');
        $server     = $this->getRequest()->getServer();
         
        //check is device is Mobile
        $isMobileDevice = \Zend_Http_UserAgent_Mobile::match($userAgent, $server);
        if ($isMobileDevice) {
            $resultPage->getConfig()->getTitle()->set(__("View For Mobile"));
        }

        //check is device is Desktop
        $isDesktopDevice = \Zend_Http_UserAgent_Desktop::match($userAgent, $server);
        if ($isDesktopDevice) {
            $resultPage->getConfig()->getTitle()->set(__("View For Desktop"));
        }
        return $resultPage;
    }
}

Hope this will be helpful. Thanks 🙂

Previous Blog: Reindexing for one product in Magento 2


Viewing all articles
Browse latest Browse all 5557

Latest Images

Trending Articles



Latest Images