46

Is there a way to get the anchor part of a URL in a controller?

Example: if I type http://www.foo.com/bar#anchor123 can I get the string anchor123 in my controller?

atw
  • 5,428
  • 10
  • 39
  • 63
Pioz
  • 6,051
  • 4
  • 48
  • 67

2 Answers2

48

You can't do that in Rails, because the anchor is not sent to the server. See mikeduncan.com/?s=named+anchors

vmarquet
  • 2,384
  • 3
  • 25
  • 39
True Soft
  • 8,675
  • 6
  • 54
  • 83
34

No sorry, it's not possible to retrieve the #anchor from the server-side (in any language).

This is a client-side flag to tell the browser to move to a specific position in the page.

But you can use some Javascript in the body to check for an anchor and send it back to the server using an Ajax-call...

var anchor_value;
var stripped_url = document.location.toString().split("#");
if (stripped_url.length > 1)
  anchor_value = stripped_url[1];
Nicolas Blanco
  • 11,164
  • 7
  • 38
  • 49
  • 1
    Might be nicer to use `window.location.hash` to get the value of the anchor rather than `split`ting..? https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash – Dan Eastwell Jul 31 '18 at 08:40