Diogenes Painting by Jean Leon Gerome |
I'm in a platform that only accepts a page as home page HTML. In my case my login page.
I needed that if the login had not success, then one message would be passed to this same page be reloaded, reading and showing the message.
I did not want to create a second page that is always overlooked when changing the layout or css.
After a little search I wrote the follow code:
to use, create a HTML file like: parametro.html
open with your browser, type something like:
file:///yourfolder/parametro.html?param=Hello World¶m2=21/12/1966
<!DOCTYPE HTML>
<HTML LANG="pt-br">
<HEAD>
<SCRIPT>
/**
* Example of how to read the parameters of
* a URL when loading a page using javascript
* @author Nivio dos Santos
* @version 1.0
*/
/**
* Creating namespace in order to avoid naming conflict.
*/
nivio = function(){};
nivio.context = function(){};
/**
* Static method that can be triggered
* when loading the page capturing the parameters.
*/
nivio.context.pageLoaded = function()
{
var indice = document.URL.indexOf("?");
if(indice > -1)
{
nivio.context.params = new nivio.context.ObjParam();
// shortcut reference
var objParam = nivio.context.params;
// SEPARATE MESSAGE
var message = document.URL.substr(indice+1);
// SEPARATE PARAMETERS
var tuples = message.split("&");
for(var i=0;i<tuples.length;i++)
{
var param = tuples[i].split("=");
if( param.length > 1)
{
objParam.addParam( param[0], param[1] );
}
else
{
objParam.addParam( param[0], '' );
}
}
}
}
/**
* Class to hold the parameters
* @constructor
* @this {ObjParam}
*/
nivio.context.ObjParam = function(){};
/**
* Creates a new Circle from a diameter.
*
* @this {ObjParam}
* @param {String} key to parameter value
* @param {String} value
*/
nivio.context.ObjParam.prototype.addParam = function(key,value)
{
this.keys = this.getKeys();
this.keys.push( key );
this[key] = decodeURIComponent(value);
}
/**
* Get list of keys.
* @this {ObjParam}
* @return {Array<String>} The new Circle object.
*/
nivio.context.ObjParam.prototype.getKeys = function()
{
if( this.keys == null || this.keys == undefined )
{
this.keys = new Array();
}
return this.keys;
}
/**
* Get key associated parameter value
* @this {ObjParam}
* @return {String}
*/
nivio.context.ObjParam.prototype.getParam = function(key)
{
return this[key];
}
/**
* Teste
*/
function teste()
{
var texto="";
var objParam = nivio.context.params;
var keys = objParam.getKeys();
for(var i=0;i<keys.length;i++)
{
texto = texto +"<br>"+ keys[i] + "=" + objParam.getParam( keys[i] );
}
var areaT = document.getElementById("areateste");
areaT.innerHTML = texto;
}
</SCRIPT>
</HEAD>
<BODY onload="nivio.context.pageLoaded()">
<INPUT TYPE="BUTTON" VALUE="TESTE" ONCLICK="teste()">
<HR>
<DIV ID="areateste">
</BODY>
</HTML>
Comments
Post a Comment
Thanks for your attention and feedback.
Nivio dos Santos