Obtaining Iframe src from Query String Data
This portion of the Iframes Tutorial provides JavaScript for specifying which documents should load in iframes based on data obtained from query string parameters. An example demonstrates and provides more information.
Setting up Links and Parameters
The JavaScript provided here enables links to pages containing iframes to indicate which page should load in a specific iframe by including data in the query string. An example link could be set up as follows:
<a href="your_page.html?ifrm=pg1">[link text here]</a>
Notice that the query string does not specify the iframe's URL directly, but instead includes the id of the iframe (ifrm) and a lookup value for the URL (pg1). Data for more than one iframe can be provided in the query string.
The code uses object literals to specify the ids of iframes and lists of URLs to allow. This keeps the query parameters for the code short and clean and also prevents problems that can result from accepting arbitrary data that a user might place in the query string.
About the Code
The JavaScript to provide this functionality is brief, consisting of only two functions. The first, .getValueFromQueryString, is a utility function to obtain values from the query string. The second function, checkQuery4Iframe, checks the query string to see it if it provides data appropriate for loading iframes according to information you have provided.
You set up the data to pass to checkQuery4Iframe in an object literal. You include the id of the iframe and lookup values and URLs that may be displayed in this iframe: The following demonstrates the means of providing data for a specific iframe:
var iframe_props = {
id: 'ifrm', // id of iframe
urls: { // lookup values and urls to load in iframe
'dflt': 'your.html', // a default page
'pg2': 'your2.html',
// full URL example
'pg3': 'http://www.yourdomain.com/page.html'
}
};
You can place the call to the checkQuery4Iframe function below the iframe, or you can call it onload or using some version of document.ready:
checkQuery4Iframe(iframe_props);
If your document includes more than one iframe, you can includes more object literals containing properties and URLs for each of them, following the pattern demonstrated above, and include additional calls to checkQuery4Iframe.
An example demonstrates and provides more information about the code.