Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can URL tell jQuery to run a function?

Have a question regarding URL and jQuery.

Can I specify URL to tell jQuery to run a function?

e.g http://www.website.com/about.html?XYZ

to run a function XYZ();?

like image 739
Iladarsda Avatar asked Jul 18 '11 16:07

Iladarsda


2 Answers

You can put code in that web page that examines the query parameters on the URL and then, based on what it finds, calls any javascript function you want.

In your particular example, a simplified version would be like this:

// code that runs when page is loaded:
if (window.location.search == "?XYZ") {
    XYZ();
}

or if you want it to run any function that is present there, you can extract that from the string and run whatever name is there.

// code that runs when page is loaded:
if (window.location.search.length > 1) {
    var f = window.location.search.substr(1);  // strip off leading ?
    try {
        eval(f + "()");  // be careful here, this allows injection of javascript into your page
    } catch(e) {/* handler errors here */}
}

Allowing arbitrary javascript to be run in your page may or may not have undesirable security implications. It would be better (if possible) to support only a specific set of pre-existing functions that you look for and know are safe rather than executing arbitrary javascript like the second example.

like image 84
jfriend00 Avatar answered Nov 14 '22 17:11

jfriend00


In the URL bar you can always put javascript:XYZ();

Try that after this url loads: http://jsfiddle.net/maniator/mmAxY/show/

like image 44
Naftali Avatar answered Nov 14 '22 16:11

Naftali