Things we can do with location.search
by, 01-01-2013 at 09:42 PM (16603 Views)
We can use the search portion of a URL containing a question mark - where the search portion is the string to the right of '?' - to pass data from one page (our_file.html) to another (our_file.html?this is a test). Here's a script that we could use for that purpose. It must be put immediately before the closing body tag of the page (here: our_file.html)
data = location.search.substring(1); // needed to remove the '?'
//do something with the data
A more interesting example of passing data from one page to another using the search portion of a URL is the following, which assumes that (i) we have an iframe in our_file.html: <iframe name="ifr" style="position: absolute; width: 300px; height: 300px; background: white" src="some_page.html"></iframe> and that (ii) //do something with the data in the script above is replaced with ifr.location.replace(data). If we now replace our original link in our_file.html with <a onclick="location.search='some_other_page.html'">some other page</a>, a click on the new link will take us to a new page our_file.html?some_other_page.html which is identical to our_file.html except for the content of the iframe, which loads some_other_page.html (in our_file.html?some_other_page.html). Of course, in order for this to work, we must create two pages some_page.html and some_other_page.html first.
This demonstrates that location.search can be used to (i) preserve the content of a given page (here: our_file.html) and, at the same time, to (ii) change the content of an iframe contained in it while going from one page to another page (here: our_file.html?some_other_page.html). So a navigation menu in the 'main page' (here: our_file.html) will be visible on all pages of a site constructed along the lines given here.
IMPORTANT: <a onclick="location.search='some_other_page.html'">some other page</a> was used above in a non-iframed page to go from some_page.html (in an iframe) to some_other_page.html (in an iframe). If we want to change the iframe's content from within the iframe, we should do <a onclick="parent.location.search='some_other_page.html'">some other page</a>.
Demo and explanations here. The demo contains features that have nothing to do with location.search, because I already used the files of the demo for another purpose. But I think it explains rather what I want to show.