Search code examples
javascriptregexurlhref

Errorproof way to define active link in HTML, based on current URL in address bar


The link in the HTML might be an absolute path or a relative one
It might have query parameters or not
It might have a hash or not

The current URL can similarly be/have anything

Is there a safe/errorproof JS way to check whether a link in the HTML is the "active" one by comparing it to the current URL ?

I assume some regex will have to be used on the <a href> and another one on the address bar URL and compare the two but is there a known/standard way of successfully achieving this?

I wanted to check whether this is already known to be bound to fail, before I actually start trying out solutions :D

Thanks!


Solution

  • Is there a safe/errorproof JS way to check whether a link in the HTML is the "active" one by comparing it to the current URL ?

    It depends on whether you want to consider the query parameters and/or hash.

    The relative/absolute thing isn't a problem, use the anchor element's href property (not attribute), which will be resolved (absolute). Or use the anchor element's various individual parts (protocol, host, etc.). Anchor elements include the HTMLHyperlinkElementUtils mixin:

    interface mixin HTMLHyperlinkElementUtils {
      [CEReactions] stringifier attribute USVString href;
      readonly attribute USVString origin;
      [CEReactions] attribute USVString protocol;
      [CEReactions] attribute USVString username;
      [CEReactions] attribute USVString password;
      [CEReactions] attribute USVString host;
      [CEReactions] attribute USVString hostname;
      [CEReactions] attribute USVString port;
      [CEReactions] attribute USVString pathname;
      [CEReactions] attribute USVString search;
      [CEReactions] attribute USVString hash;
    };

    If you want to include the query parameters and hash, then

    if (link.href === location.href)
    

    Remember that query parameter order can be significant. It often isn't significant, in which case the above will fail for "equivalent" URLs such as http://example.com?foo=a&bar=b and http://example.com?bar=b&foo=a if, for that resource, the relative order of foo and bar isn't significant. In that case, you'd have to parse the query parameters and compare such that the resource's rules for when and where order matters are taken into account. (In most cases, for instance, ?foo=1&foo=2&bar=x and ?foo=2&foo=1&bar=x would not be the same thing, but ?foo=1&foo=2&bar=x and ?bar=x&foo=1&foo=2 and ?foo=1&bar=x&foo=2 would be. But again, it's resource-specific.)

    If not, you'll need to pick out the parts that you consider the same and compare those. location supports the individual parts like anchor elements do (protocol, host, etc.).