Here's an interesting bug in Internet Explorer I ran across today:
When using window.location to go to a named anchor inside of an iframe, using a String object versus a string primitive produces different results.Okay, it's pretty hard to explain, let's look at a demo. We need two source html files, a main outer page, and a page for the iframe.
main.html
<html>
<head><title></title></head>
<body>
<p>MAIN CONTENT</p>
<iframe src="iframe.html" width="200px" height="250px"></iframe>
</body>
</html>
iframe.html
<html>
<head>
<title></title>
<script type="text/javascript">
function run() {
window.location = new String("#here");
}
setTimeout("run()", 2000);
</script>
</head>
<body>
... Some breaks ...
<a name="here" />
</body>
</html>
When main.html is opened in Internet Explorer 6 (try it), the iframe doesn't move to the anchor, instead it refreshes itself with the contents of it's containing html page -- main.html. Huh? If we change set window.location to "#here" instead of instantiating a new String object, it works as expected (try it). What is going on here? Let us try to break down the line in question.
Javascript's string primitives and String Objects
Javascript provides both string primitives and String objects1. A string object is created by new String(""), whereas a primitive is declared by quotes. The object contains methods like charAt and properties like length and is automatically instantiated anonymously if you write something like: "hello world!".length.
window.location
The location object is special. Isn't it? You can set it to a string, or any of it's properties. Could IE be confused when objects are being passed in? Maybe confusing a string object with a location object?
Anyone have any other ideas?
Of, course, the better way to go to an anchor on the current page is setting the hash property of the location object. Using a string primitive versus a String object both work equally well. Here's an example.
// Both of these work
window.location.hash = 'top';
window.location.hash = new String('top');
2 Comments
Leave a comment
0 TrackBacks
Listed below are links to blogs that reference this entry: Javascript Puzzler.
TrackBack URL for this entry: http://www.nearinfinity.com/mt/mt-tb.cgi/461



a
15 penis enlargement devices, 10 penis enlargement patches.