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; } }
Note: In the latest version of Magento, you can face Zend_Http_UserAgent_Mobile is deprecated error. So, for Magento’s latest version, please refer to the following blog:
https://webkul.com/blog/how-to-detect-the-mobile-devices-in-the-latest-magento-as-zend_http_useragent_mobile-is-deprecated/
Hope this will be helpful. Thanks 🙂
Previous Blog: Reindexing for one product in Magento 2
Next Blog: Override Product Special Price in Magento 2
Be the first to comment.