0

I'm trying to call a function given the function name in the hash string. I have the following code:

$(window).on('hashchange', function() {
  //alert(location.hash.substring(1, location.hash.length));
  window[location.hash.substring(1, location.hash.length)];
});

function test() {
  alert('123!');
}

The funny thing is, when I uncomment the alert call, everything works as expected. When the alert is commented, however, it doesn't work.

Any ideas?

David Jones
  • 10,117
  • 28
  • 91
  • 139
  • 4
    Where are you calling a function ? – Denys Séguret Dec 20 '12 at 19:03
  • Sounds like what you are trying to do will open a [major XSS hole](https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)) – Bergi Dec 20 '12 at 19:58
  • @Bergi: I'm only using this for page navigation within a mobile web app. The functions that are called serve the purpose of rendering the page via API calls, which requires authentication, so I don't think it really opens up a security risk (but correct me if I'm wrong). Thanks! – David Jones Dec 20 '12 at 20:11
  • Do these API calls change something or are they only GET requests? Authentication might have happened before, so the user does not notice what happens. Also, this code allows execution of arbitrary (and possibly unwanted) functions, try to open `www.yourpage.com/#alert`. So put these function on their own object, not the global window object, and you can control which (callable) properties it has. – Bergi Dec 20 '12 at 20:20

1 Answers1

4
window[location.hash.substring(1, location.hash.length)];

doesn't call a function.

If you want to call the function whose name is location.hash.substring(1, location.hash.length), you may do

window[location.hash.substring(1, location.hash.length)]();

Side note :

location.hash.substring(1, location.hash.length)

can be shortened in

location.hash.slice(1)
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758