Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious variable "URL" inside inline event handlers

In the following code, what would you see in the alert dialog when you click on click here?

<script>
URL = 'hello' ;
document.write(URL) ;
</script>
<div onclick="alert(URL)">click here</div>

Fiddle

I was so sure the answer would be "hello" that I did not even care to try it.
But what I actually see is the url of the current page (tested on Chrome, Firefox and IE9).

Why is this URL varaible defined inside inline event handlers?
Why does it take precedence over my own variable?
Where can I find documentation about this behaviour?


Follow-up

Is this meant to happen only inside inline event handlers?
What's the motivation for something like this?


Follow-up 2

I did more testing on old browsers and this behavior seems to be an trace from ancient times. I verified it on the following browsers:

  • Mozilla 1.0.1
  • Firefox 2.0.0.6
  • IExplorer 6.0
  • Nestscape 8.1.2
  • Opera 9.02

Which means this URL variable is definately not the experimental window.URL function/constructor. It is a string and it exist only inside inline event handlers.

like image 383
GetFree Avatar asked Jan 08 '14 00:01

GetFree


1 Answers

The variable window.URL (that is, the global variable URL) is special. (Change your script to use another name, such as url, and it will behave as you originally expected.) Some documentation about URL can be found here. Note that browsers that do not support URL will not behave in this unexpected way.

Well, the above was not quite right. There are two URL variables in play here. When the script runs, it overwrites (or creates) window.URL, which is then written to the document. (Note that your code wipes out window.URL, so once your script runs, you no longer can do things like var n = new URL(...); in browsers that supported that technology.)

On the other hand, when the <div> is created, the onclick handler attribute value is converted to the function:

function() {
    alert(URL);
}

The important thing, which explains the behavior) is that the conversion from a string to a function is carried out in the context of document. Thus the URL in this function refers to document.URL. (The document.URL property is described here.) You can verify this by exercising the following:

<script>
URL = 'hello' ;
document.write(URL);
</script>
<div onclick="alert(URL === document.URL)">click here</div>
like image 82
Ted Hopp Avatar answered Nov 09 '22 07:11

Ted Hopp