Find your content:

Search form

You are here

How do I isolate the anchor (#anchor) portion of a URL?


If I navigate to the following Visualforce URL:

... I'd like to be able to isolate the Anchor value via Apex. I've tried both of these approaches, which the documentation suggests should work:

  • Using System.URL: URL.getCurrentRequestUrl().getRef()
  • Using ApexPages: ApexPages.CurrentPage().getAnchor()

These both return blank/null values. What am I missing, and how do I get the anchor from the URL?

Attribution to: Benj

Possible Suggestion/Solution #1

String link = '';
URL u = new System.URL(link);

System.debug(u.getRef()); // works for me, outputs "Anchor"

So I think you'll have to experiment with what kind of source string these methods return. Play with toExternalForm()?

Attribution to: eyescream

Possible Suggestion/Solution #2

Assuming, that the anchor is not available directly in the controller, you could process the URL in an onLoad function and then pass the value to the controller either via an actionFunction or using Javascript Remoting

<script type="text/javascript" >
 window.onload = function(){

     var achorElement = window.location.hash.substring(1);
     setAnchor(achorElement); //invoke action function

 <apex:actionFunction name="setAnchor" >
    <apex:param assignTo="{!anchorElement}" value="" /> //pass parameter to controller


Attribution to: techtrekker

Possible Suggestion/Solution #3

It's not an answer, but I think javascript is going to be your only option. If that's a deal breaker switch from using the anchor as a parameter.

The only access you have to the url is via the ApexPages.currentPage().getUrl() or Url.getCurrentRequestUrl() and both have pre-processing that strips out the anchor. It's not documented, but it can be a pain in the ass if you're trying to redirect to page with an anchor.

For example:

String url = '/anotherPage?param=value#anchor';
PageReference pr = new PageReference(url);
system.assertEquals(url, pr.getUrl());

Results in:

Assertion Failed: Expected: /anotherPage?param=value#anchor, Actual: /anotherPage?param=value

Attribution to: Ralph Callaway

Possible Suggestion/Solution #4

It looks like from Spring'14 onwards you will be able to handle this in PageReference....

PageReference URIs Support Anchors. A PageReference is a reference to an instantiation of a page. Among other attributes, PageReferences consist of a URL and a set of query parameter names and values. You can construct PageReference objects with URIs that include anchors or fragment identifiers, that is, an identifier following a hash symbol (#).

Nice! :-)

Attribution to: Andrew Fawcett
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content