Passing URL parameters to client only
I wanted to implement a search plugin for the Just Search Portal so searching shortcuts built into browsers could be used to pull up the portal conveniently. To make this work, the portal must support retrieving queries from the URL like other search engines, for example: http://www.bing.com/search?q=my+search+terms
.
There is an issue, though. Resolving an URL like that, with a ?
before the query terms, would result in sending the query to the server for processing. With the Just Search Portal's focus on privacy, this is not acceptable at all. One of the main ideas is to give the user control over where the query is sent and where it is not. The query must not be sent to the webserver hosting the Just Search Portal.
The solution
It turns out there is a simple and effective way to use an URL for conveying information without sending it to the server - the URL fragment. For example, with an URL like: https://en.wikipedia.org/wiki/URL#Syntax
, the "Syntax" part is not sent to the web server, it stays client side for the browser and JavaScript to access. The original purpose of this is to link to an anchor on the page, as in the Wikipedia example, but it can be processed by JavaScript for other purposes. Here is how I did it:
<script>
function handleHashChange() {
var hash_loc = window.location.hash;
/* Handle the fragment identifier of the URL on page load or when changed */
}
window.onhashchange = handleHashChange;
handleHashChange();
</script>
Demonstration
To demonstrate the difference, here is first how a browser would handle an URL with a typical ?
seperated parameter: /?query=
. Note that the Just Search Portal can't use a query formatted like this, it is just for the example.
The network monitor is opened with F12 to show exactly what happens:
The query is sent to the web server by the name of the File requested: /?query=abc
. The server responds by transferring the Just Search Portal page 841 ms later.
Here's the situation where the query is encoded as an URL fragment: /#query=abc
The web server is now being asked for the root file only: /
but the browser has this in cache already, so the web server is not even being contacted! The JavaScript then transfers the query from the URL fragment to the search bar.
So, a great added benefit of this method is a lightning fast page load and a much reduced load on the web server.
I hope you enjoyed this content!
Comments powered by Talkyard