Location hack: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
(comment4,)
(comment4,)
Line 7: Line 7:
comment4,
comment4,


== Executing large blocks of code ==
comment4,
 
Executing more than one statement can become unreadable very easily. Luckily, JavaScript can convert functions to strings, so you can use:
 
location.href = "javascript:(" + function() {
  // do something
} + ")()";
 
Even though the function is defined in the sandbox, it is not a closure of the sandbox scope. It is converted to a string and then back to a function in page scope. It cannot access anything in the sandbox scope, which is a limitation, but is also essential to making this technique secure.


== Percent encoding issue ==
== Percent encoding issue ==

Revision as of 12:46, 9 August 2011

The location hack is an ugly but useful way to interact with the content scope of the page being user scripted. It does this by indirectly evaling strings within that scope.

comment5,

comment4,

comment4,

comment4,

Percent encoding issue

Sometimes percent-encoding the percent symbol is required. For example,

location.href = ("javascript:(" + function() {
  var n = 44;
  if(!(n%22)) alert('n is a multiple of 22');
} + ")()");

The above code will cause error because %22 is interpreted as double quotation mark. The workaround is:

location.href = "javascript:(" + encodeURI(
 function() {
  var n = 44;
  if(!(n%22)) alert('n is a multiple of 22');
 }) + ")()";

See also encodeURI().

Returning values

The location hack is really handy for passing values to the content scope, or to call functions defined there. It is not, however, capable of directly reading a variable or value returned from a function. Furthermore, it is run asynchronously, much like setTimeout(), so you cannot immediately rely on side effects. (If you use the location hack to, for example, store a value in the DOM and then attempt to read it, it will only be available at some other later point in time.) For reading javascript values from the content scope inside the sandbox, see Reading Content Globals for a reliable example.

See Also