Brett Sutton
Brett Sutton

Reputation: 4584

Anchor not relative to window.location

I have a single page app which contains anchors to in-page links (#xxx):

The browser address bar shows: https://example.com/packages/get

My tag is written as:

<a href="#later-in-the-page">go to later in the page</a>

When I hover my mouse over the anchor the browser shows the link as:

https://example.com/#later-in-the-page

However I'm expecting the anchor to url to show as:

https://example.com/packages/get/#later-in-the-page

When I inspect window.location it is showing:

{
    "ancestorOrigins": {},
    "href": "https://example.com/packages/get",
    "origin": "https://example.com",
    "protocol": "https:",
    "host": "example.com",
    "hostname": "example.com",
    "port": "",
    "pathname": "/packages/get",
    "search": "",
    "hash": ""
}

I am using a client side package (vaadin) that hooks the clicks on the anchor tag but I don't see how that can be affect what the anchor shows.

Finally, when I click the link it transitions to the sites home page rather than just scrolling down the page.

Edit: I've played around with setting the <base> tag to /packages/get and the result is that the tag shows correctly but

  1. I don't believe I should have to do this
  2. I've read that its not recommend - but I'm not certain as to why
  3. this could be a little tricky to do.

Upvotes: 0

Views: 164

Answers (1)

Leif &#197;strand
Leif &#197;strand

Reputation: 8001

What you have encountered is the bane of single page applications. There are two bad alterantives:

  • Leave the base href untouched which means that in-page anchors work as expected while URLs to load application resources need to compensate for the current location (e.g. ../../images/logo.png). (Vaadin cannot assume the application is deployed to a root URL, so /images/logo.png wouldn't always work.)
  • Point the base href to the location where the application is deployed to make resource loading easier, but instead making it more difficult to reference things relative to the current page (such as in-page anchors).

Vaadin has chosen to set the base href. You will cause problems with everything else on the page that references things on the server if you change it.

This means that any in-page anchor links need to compensate by explicitly also including the current route in the URL. In your case, that would mean setting href to e.g. packages/get/#later-in-the-page.

Upvotes: 2

Related Questions