8

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 ?

2 Answers 2

16

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();
1
  • hi @Marius, can we get controller ad action name from getRefererUrl? Dec 11, 2018 at 9:39
6

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();

6
  • fyi i'd avoid the die here, also no need to assign to var. execute can just return $this->redirect->getRefererUrl(); Nov 30, 2018 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.. Dec 3, 2018 at 5:40
  • @ManiMaranA, how to check if the referral url us forgot password page? Dec 11, 2018 at 9:26
  • can we get controller and action name from getRefererUrl? Dec 11, 2018 at 9:39
  • try this... $url = 'test.com/customer/account/forgotpassword'; if (strpos($url,'forgotpassword') !== false) { echo 'Forget Password page'; } else { echo 'other page.'; } Dec 13, 2018 at 2:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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