4

How to get RefererUrl (source page url) in Observer file?

Actually by using this;

$this->_redirect->getRefererUrl();

I am getting Referer Url in magento 2 controller file.But in Observer file I am not getting the source url (RefererUrl).

Can you help me on this ?

12

Make your observer class look like this:

namespace Vendor\Module\Observer;

class ClassNameHere implements \Magento\Framework\Event\ObserverInterface
{
    protected $redirect;
    public function __construct(
        ....
        \Magento\Framework\App\Response\RedirectInterface $redirect,
        ...
    ) {
        ...
        $this->redirect = $redirect;
        ....
    }
}

then you can get the referer url in your execute method like this

$redirectUrl = $this->redirect->getRedirectUrl();
| improve this answer | |
  • hi @Marius, can we get controller ad action name from getRefererUrl? – jafar pinjar Dec 11 '18 at 9:39
5

yourObserverFile.php

class ClassNameHere implements \Magento\Framework\Event\ObserverInterface
{
    protected $redirect;
    public function __construct(
        ....
        \Magento\Framework\App\Response\RedirectInterface $redirect,
        ...
    ) {
        ...
        $this->redirect = $redirect;
        ....
    }
   public function execute(\Magento\Framework\Event\Observer $observer)
    {
     return $redirectUrl = $this->redirect->getRefererUrl();
    }
}

Following line will help you to get refferer Url.

$this->redirect->getRefererUrl();

| improve this answer | |
  • fyi i'd avoid the die here, also no need to assign to var. execute can just return $this->redirect->getRefererUrl(); – Mark Shust at M.academy Nov 30 '18 at 15:02
  • i know, this is the solution code, anyone can test, i have added and printed refferer url for others who dont understand easily, you dont want to use die or echo...just do return.. – ManiMaran A Dec 3 '18 at 5:40
  • @ManiMaranA, how to check if the referral url us forgot password page? – jafar pinjar Dec 11 '18 at 9:26
  • can we get controller and action name from getRefererUrl? – jafar pinjar Dec 11 '18 at 9:39
  • try this... $url = 'test.com/customer/account/forgotpassword'; if (strpos($url,'forgotpassword') !== false) { echo 'Forget Password page'; } else { echo 'other page.'; } – ManiMaran A Dec 13 '18 at 2:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.