Client-Side URL Parameter Parsing for HTML Components

It is often very useful to pass parameters to frames and HTML5 components of a page. Here is a simple solution for client-side only processing of parameters.

The context of this pattern, depicted in the sequence below, is usage of frames with <object/> tags in HTML5, or <iframe/> tags in legacy applications; this technique allows modularization of large HTML files and support CMS. As the browser loads the page with embedded frames, it loads the content of each frame separately, executing the JavaScript it refers to. This post refers to the JavaScript code specified in each frame which parses location.href to extract the URL parameters.

BLOG-Client-Side-Parameters

An example <object/> and <iframe/> tag is provided below. HTML5 forward looking applications should use <object/>, however backwards compatibility with older browsers (e.g., IE8) requires the use of <iframe/>.

HTML code for embedding components.

<object data="?v=option1&q=..." title="component description" type="text/html" style="..." />
. . .
or
. . .
<iframe src= "?v=option1&q=..." title="component description" style="..." ... />

The JavaScript code provided below for extracting URL parameters relies RegEx. Note that in case a parameter contains a parameterised-URL string, the ‘&’ needs to be URL encoded as %26.

JavaScript code to parsing URL parameters.
<script>
var params = {}
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function (m, key, value) { params[key] = value; });

.
.
.
var v = params[‘v’];
.
.
.
</script>

This technique is also applicable to pages without frames, whereby the client-side code can be modified to consume parameters without impact to the server side code. This enables, for example, modifying functionality of a Web-Role without re-deployment, and often, without a restart; this detail is left for another post.

In other situations, it may be advantageous to design the server side code to parse the URL parameters prior to generating the HTML page. Subsequently, as the page loads, the client side JavaScript parses the location.href to act upon the URL parameters, independently of the server.

Leave a comment

Who's the Coach?

Ben Ruiz Oatts is the insightful mastermind behind this coaching platform. Focused on personal and professional development, Ben offers fantastic coaching programs that bring experience and expertise to life.

Get weekly insights

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.