Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Previous page location on IronRouter

Is there a way to get the previous page location before going to the next page in IronRouter?

Is there an event I can use to fetch this information?

Thanks in advance.

like image 866
Luca Avatar asked Sep 19 '14 09:09

Luca


3 Answers

Since Iron Router uses the usual History API, you can just use the plain JS method:

history.go(-1);

or

history.back();

Edit: or to check the previous path without following it:

document.referrer;

like image 56
Hubert OG Avatar answered Nov 16 '22 12:11

Hubert OG


You can achieve the behavior you want by using hooks.

// onStop hook is executed whenever we LEAVE a route
Router.onStop(function(){
  // register the previous route location in a session variable
  Session.set("previousLocationPath",this.location.path);
});

// onBeforeAction is executed before actually going to a new route
Router.onBeforeAction(function(){
  // fetch the previous route
  var previousLocationPath=Session.get("previousLocationPath");
  // if we're coming from the home route, redirect to contact
  // this is silly, just an example
  if(previousLocationPath=="/"){
    this.redirect("contact");
  }
  // else continue to the regular route we were heading to
  this.next();
});

EDIT : this is using iron:[email protected]

like image 32
saimeunt Avatar answered Nov 16 '22 10:11

saimeunt


Apologies for bumping an old thread but good to keep these things up to date saimeunt's answer above is now deprecated as this.location.path no longer exists in Iron Router so should resemble something like the below:

Router.onStop(function(){ Session.set("previousLocationPath",this.originalUrl || this.url); });

Or if you have session JSON installed (see Session JSON)

Router.onStop(function(){ Session.setJSON("previousLocationPath",{originalUrl:this.originalUrl, params:{hash:this.params.hash, query:this.params.query}}); });

Only caveats with thisis that first page will always populate url fields (this.url and this.originalUrl there seems to be no difference between them) with full url (http://...) whilst every subsequent page only logs the relative domain i.e. /home without the root url unsure if this is intended behaviour or not from IR but it is currently a helpful way of determining if this was a first page load or not

like image 1
Philip Pryde Avatar answered Nov 16 '22 10:11

Philip Pryde