1

I have a "copy link" input in my template that should display the currently loaded URL (with query params) to the user for them to copy & paste.

The input with the URL is part of the template belonging to a parent route that has a number of children:

- Parent route  <-- Copy URL link in this template
  - Child route
  - Child route
  - Child route

This means that as you navigate the child routes, the URL should update in the parent route. This is turning out to be very difficult to implement.

  • AFAIK there is no native event for URL change so I can't create a component and simply track any browser event. I tried hashchange on the window but this obviously only tracks the #and not URL or query params.
  • I can't use window.location.href when the page loads as any subsequent transitions to the child routes will not be reflected in the input.
  • I can't get the URL with window.location.href in the didTransition action (or any other route hooks) on the parent route because at that point the URL hasn't updated yet (i.e. I get the previous URL)

EDIT:

At the moment, this is the only approach that seems to work:

// In the parent route:
actions: {
  didTransition() {
    this._super(...arguments);
    Ember.run.schedule('afterRender', () => {
      this.set('controller.currentURL', window.location.href);
    });      
  }
}

but seems pretty hacky

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177

2 Answers2

2

Since Ember 2.15 you can use the route service for this.

Example:

import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed';

export default Component.extend({
  router: service(),
  currentRoute: alias('router.currentURL')
});  

1

I think you can benefit from router's location's path property. What I mean is, you can inject router to the controller you like with an instance-initializer and define a computed property to watch the current path. Please check out the following twiddle. I wrote an instance initializer named instance-initializers\routerInjector to inject application's router to every controller. I defined a computed property named location within application.js controller as follows:

location: Ember.computed.oneWay('router.location.path')

I added this to application.hbs. If I got what you want correctly; this is what you want.

feanor07
  • 3,328
  • 15
  • 27