Javascript, Variables en URL como Anchors

From Wiki de Caballero
Jump to navigation Jump to search

Hay algunos sitios que utilizan frames, iframes o partes variables adentro de la misma página. Esto es útil a la hora de programar pero puede tener un problema de usabilidad para el lector de la página, si quieres mandar el link exacto a un amigo o guardar el link en favoritos por ejemplo, se guarda el URL de la página sin las modificaciones internas o el iframe correcto.

Para solucionar esto, se puede usar un truco, usar la parte de los anchors del URL para guardar variables, todo con javascript.

A continuación hay un ejemplo de una librería básica para llevar a cabo esta idea. Primero el uso de la librería y luego el código.

Uso

Guardar el código en un archivo llamado params.js, en el html cargar el archivo y usar las siguientes funciones.

params.setParam(paramName,paramValue) // para setear un parametro, lo guarda en la URL
params.getParam(paramName)	      // para obtener lo que contiene el parametro, lo obtiene de la URL

Código

//*****************************************************************
//	By Flat Estrategia Digital <http://www.flat.cl/>
//	<contacto@flat.cl>
//	Created By: Felipe Caballero, Feb 19, 2010
//		Description:
//	This object is used to set/retrieve variables from the
//	anchor part of the URL
//*****************************************************************
var params = {
	nameList: null, // List of Params names
	valueList: null, // List of Params values
	anchs: null, // Initialized with the values in hash part of URL
	// Next function sets a new parameter in the hash part or URL
	setParam: function(param, val) {
		this.retrieveParams();
		if (this.anchs == "")
		{
			location.hash = param + "/" + val;
			return;
		}
		else
		{
			var urlParams = "", createNewParam = true;
			for (i = 0; i < this.nameList.length; i++)
			{
				if (this.nameList[i] == param)
				{
					this.valueList[i] = val;
					createNewParam = false;
					break;
				}
			}

			if (createNewParam)
			{
				var nameTemp, valueTemp;
				nameTemp = new Array(this.nameList.length + 1);
				valueTemp = new Array(this.nameList.length + 1);
				for (i = 0; i < this.nameList.length; i++)
				{
					nameTemp[i] = this.nameList[i];
					valueTemp[i] = this.valueList[i];
				}
				nameTemp[nameTemp.length - 1] = param;
				valueTemp[valueTemp.length - 1] = val;
				this.nameList = nameTemp;
				this.valueList = valueTemp;
			}

			for (i = 0; i < this.nameList.length; i++)
			{
				if (i == 0)
					urlParams += this.nameList[i] + "/" + this.valueList[i];
				else
					urlParams += "&" + this.nameList[i] + "/" + this.valueList[i];
			}
			location.hash = urlParams;
		}
	},
	// Next function gets a new parameter in the hash part or URL
	getParam: function(param) {
		this.retrieveParams();
		for (i = 0; i < this.nameList.length; i++)
		{
			if (this.nameList[i] == param)
			{
				return this.valueList[i];
			}
		}
		return null;
	},
	// Next function is called before other functions
	retrieveParams: function() {
		this.nameList = null;
		this.valueList = null;
		this.anchs = location.hash;
		if (location.href) {
			var paramArray = this.anchs.substr(1).split('&');
			this.nameList = new Array(paramArray.length);
			this.valueList = new Array(paramArray.length);
			for (i = 0; i < paramArray.length; i++)
			{
				this.nameList[i] = paramArray[i].split('/')[0];
				this.valueList[i] = paramArray[i].split('/')[1];
			}
		}
	}
};