2

When I type in something like

javascript:alert("test");

into the url bar, it works fine. But when I type something like

javascript:window.onclick=function(){alert('hi');}

It brings me to a page saying

function (){alert('hi');}

BTW, I am running Firefox 33. Yes, the code works if I type it into the console.

Any help would be appreciated.

0

2 Answers 2

4

Wrap it in an immediately-invoked function expression:

javascript:(function (){ window.onclick = function () { alert( "Hi" ); } }());
Sign up to request clarification or add additional context in comments.

2 Comments

Does not explain the issue the OP is facing, yes it solves it.
The issue is with the resulting value of the expression. Using an IIFE makes the overall expression evaluate to undefined, which is the key to making things work. An IIFE is not the only way to do it.
1

Alternatively, you can just make sure that your javascript: URL ends up with an undefined value:

javascript:window.onclick=function(){alert('hi');},undefined

The semantics of a javascript: URL are that the result of evaluating whatever's after the : is taken to be the URL to load, unless the result is undefined. The IIFE in Mr. Sampson's answer accomplishes that, but so does anything that leaves the result of expression evaluation undefined, as the comma-operator example above does.

It's a good idea to make sure that your javascript: URL (or bookmarklet, which is kind-of what we're talking about) is URL-encoded, though browsers are usually pretty tolerant in the URL bar. If you want to save the URL as a bookmark, I've always encoded it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.