Get current URL in emberjs

How can i get current URL in emberjs from afterModel? I tried using window.location.href but it returns url of the previous route. Also i’m using location: 'history'. Any ideas what could be the problem?

1 Like

To get the current url from a route instance, you can call this.get('router.url'). The reason you are getting the previous route’s URL is because of Ember’s run loop. Getting the url in afterModel resolves before the transition completes, giving you the route you were in before. To solve this you can wrap the call in an Ember.run.next:

afterModel: function (model){
    _this = this;

    Ember.run.next(function(){
        console.log _this.get('router.url')
    });
}
		
4 Likes

That’s awesome. Thanks :slight_smile:

How about transition.targetName

afterModel: function(model, transition) {
  console.log(Ember.get(transition, 'targetName'));
}
1 Like

@manoit88 That is better. Using transition promise, i can easily get url after the transition is complete. Thanks :slight_smile:

transition.then ->
  url = window.location.href

Do you know where I may find router.url in the API?

https://github.com/emberjs/ember.js/blob/master/packages/ember-routing/lib/system/router.js#L154-L163

Thanks. How did you find it?

I’ve spent some time in that module in the past fixing a bug.

1 Like