Getting URL hash location, and using it in jQuery
Asked Answered
N

7

144

I'd like to get the value after a hash in the URL of the current page and then be able to apply this in a new function... eg.

The URL could be

www.example.com/index.html#foo

And I would like to use this in conjunction with the following piece of code

$('ul#foo:first').show();

I'm kinda assuming/hoping there is some way of grabbing this, and turning it into a variable that I can then use in the second piece of code.

Nebraska answered 30/11, 2009 at 21:44 Comment(3)
I don't have any code for you, but you should make sure to sanitize the input, as this seems ripe for code injection.Ceolaceorl
Understanding that this question is almost a decade old, 'ul#foo:first' doesn't make sense since IDs must be unique, therefore adding :first to the selector is redundant, unless you're duplicating IDs which is invalid. Note that even a decade ago, repeated IDs were still invalid.Slambang
Still was wrong a decade agoAdamandeve
A
296

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;
$('ul'+hash+':first').show();

Note that this property already contains the # symbol at the beginning.

Actually you don't need the :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

In case you want to get the hash from an URL string, you can use the String.substring method:

var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

Armil answered 30/11, 2009 at 21:46 Comment(11)
Note that jQuery selectors can be used to execute custom javascript code, so using unsanitized hashes is horribly, horribly insecure. There is a half-assed fix for this in recent jQuery versions for selectors which contain a # before the injected code, but you are still at risk if you remove the # mark from the beginning of location.hash. E. g. var hash = location.hash.slice(1); $('ul.item'+hash).show().append($('#content')); this will execute a script tag put in the hash. It is a good habit to use $('body').find('ul'+hash+':first') instead of $('ul'+hash+':first').Whoever
Some browers return the hash symbol, and some don't, so it's safer to use: var hash = location.hash.replace('#', '');Darlinedarling
@Whoever When you say that "using unsanitized hashes is horribly, horribly insecure," can you explain what can be done? Are we talking about a user hacking his or her own computer? I just can't think of what the real vulnerability is and would really appreciate some elaboration.Rheostat
@snapfractalpop: as I said, script tags in the hash get executed under the right conditions. The hash can be set by the attacker to an arbitrary value by e.g. tricking the user to visit a web page controlled by the attacker and redirecting him from there.Whoever
@Tgr: let me know if I have the scenario right: Alice runs a web site, Bob is a visitor. Charlie comes along and is able to [somehow?] change the hash so that Bob gets redirected to a different link? I just want to fully understand the risk..how can Charlie affect Bob's session?Rheostat
Alice runs a web site, Bob visits it, authenticates and receives a session cookie. (Some time might pass here, Bob might even close his browser.) Charlie sends Bob a mail saying "check out this cool link!". Bob opens the link, which leads to a site controlled by Charlie. The page redirects Bob's browser to a page on Alice's site with an attack payload in the hash. The payload is executed, and since the browser still remembers the cookies, it can just send them to Charlie.Whoever
There can be other scenarios, but along the same lines. E.g. Bob is browsing Alice's site through HTTPS, from an insecure wifi connection. He is also browsing some other sites through plain HTTP. Charlie performs a man-in-the-middle attack against the HTTP connection, and injects a script which redirects to an HTTPS URL on Alice's site; the hash part of the URL is crafted to send Bob's login details to Charlie.Whoever
@Tgr, thank you for elaborating and connecting the dots. This concrete example makes me (and hopefully others) more inclined towards vigilance in keeping things secure.Rheostat
location.hash value gives old value in case of refreshing page containing iframe. So prefer to retrieve it through document.URL.indexOf('#')+1Houlihan
@Whoever You say good habit to use $('body').find(..) vs $(..) - Is that a good practice generally when you have user input?Asexual
@buffer: $(userInput) is generally unsafe because $ is overloaded and might either search for existing nodes or create new ones depending on whether the string contains <> characters. $(document).find(userInput) will always search for existing nodes so it is less unsafe. That said, the best practice is to always sanitize user input, e.g. if you use alphanumeric ids make sure it is alphanumeric.Whoever
H
37

location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL

var hash = document.URL.substr(document.URL.indexOf('#')+1) 
Houlihan answered 4/12, 2012 at 12:52 Comment(1)
Update: document.URL does not contain hash value on firefox 3.6 so location.href is safe var hash = location.href.substr(location.href.indexOf('#')+1)Houlihan
C
6

For those who are looking for pure javascript solution

 document.getElementById(location.hash.substring(1)).style.display = 'block'

Hope this saves you some time.

Changeful answered 13/6, 2016 at 10:49 Comment(0)
S
5

Since jQuery 1.9, the :target selector will match the URL hash. So you could do:

$(":target").show(); // or $("ul:target").show();

Which would select the element with the ID matching the hash and show it.

Slambang answered 3/10, 2018 at 17:39 Comment(2)
is there a way to extract the hash as a string instead of match id?Frayne
@Frayne Do you mean get the hash from jQuery's :target as a string? If so I don't believe so.Slambang
S
3

I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});
Sensory answered 18/2, 2020 at 3:36 Comment(0)
S
2

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});
Switzerland answered 15/5, 2018 at 16:37 Comment(0)
B
2

I found the marked answer wasn't sufficient for me. It states that getting the hash from the URL has huge security flaws but offers no real way of combatting it. There are ways out there of sanitizing the URL if you want to go that route, but if you're simply trying to show() a container, or apply some CSS/classes to the hash-matching ID container, then there's a much simpler way...

Introducing the :target selector.

The :target pseudo-class represents the unique element that has a matching id to the URL's fragment, meaning you can apply JS to it by simply doing something like:

$(':target').show();

Or in my case, just un-hiding the element I want with CSS only:

:target {
    display: block;
}

I know the OP's answer is almost exactly 13 years old, but this is a significantly easier and more secure way of achieving the same effect without dealing with getting the URL, splitting it up, sanitizing it - and hell, you can even avoid JS altogether with this method.

And yes, the :target selector is well-supported

Both answered 20/11, 2022 at 0:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.