Previous page location on IronRouter

半城伤御伤魂 提交于 2019-12-05 00:02:23

问题


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.


回答1:


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:router@1.0.0-pre1




回答2:


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;




回答3:


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



来源:https://stackoverflow.com/questions/25930545/previous-page-location-on-ironrouter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!