PDA

View Full Version : Is it safe to use fragment identifiers in javascript function calls?



Falkon303
11-19-2010, 09:44 AM
So, I am working on a page where I am using an ajax request, and instead of attaching "onclick" handlers to the elements, I am attaching an onclick handler to the body that sends the "location.href" to a function. From there, I parse the url using frag = location.href.split('#'), and assigning result = frag[1] From there, I use the result variable in my function/ajax call.

The reason I ask is because since it's a fragment identifier, it also gives the user complete control over what variable is passed to my function. The thing is though, since php will only be parsing it as a variable, they can't really inject a variable as a method of scripting, or are there other methods?

Additionally, I noticed you could attach an onmouseover = this.onclick(), changing the url on mouseover. It's kind of neat (if not useful for someone).

Below is the code (I took out the php/ajax request part so you all could use it if you wanted). I didn't use javascript to attach the event handlers in this example yet, but I will when making it final. I noticed triggering the "click()" in firefox didn't change the location.href as it did in explorer, so I added a function for firefox.



<script type="text/javascript">
function call(type)
{
fragment = location.href.split('#');
alert(fragment[1]);
;}

function addfrag(fragid)
{this.location.href = fragid;}
</script>
<style type="text/css">
#cell {
height:17px;
margin:3px;
FLOAT:LEFT;
padding:5px;
}

.ln {
background:#cccccc;
text-decoration:none;
height:30px;
padding-top:7px;
padding-left:5px;
padding-right:5px;
color:#666666;
border:1px solid #cccccc;
font-family:Arial, Helvetica, sans-serif;
font-size:11px;
font-weight:bold;
margin:3px;
float:left;
cursor:pointer;
}

.ln:hover {background:#ffffff;color:#E15A33;border:1px solid #E15A33;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body onmouseup="call();">
<div id="categories" name="categories">
<a id="cell" onFocus="this.blur();" onMouseOver="addfrag(this.href);" class="ln" href="#section1">section 1</a>
<a id="cell" onFocus="this.blur();" onMouseOver="addfrag(this.href);" class="ln" href="#section2">section 2</a>
<a id="cell" onFocus="this.blur();" onMouseOver="addfrag(this.href);" class="ln" href="#section3">section 3</a>
</div>