Search code examples
javascriptbookmarklet

How to get the source of a javascript bookmark from itself when running?


I have a bookmark that's a JavaScript bookmark. For example:

javascript:alert('hi');

I'd like to be able to get the source of the currently running JavaScript bookmark, from within the bookmark itself, so in pseudocode:

javascript:alert(currentlyExecutingScript.text);

Which would alert

javascript:alert(currentlyExecutingScript.text);

How can I do this? I prefer cross browser solutions, but am completely fine with just Chrome specific solutions!

Why am I interested in this? Because I'm writing a bookmarklet that refers to itself.


Solution

  • As location refers to the current page's URL, and JavaScript bookmarks do not change location, this is not possible in any current browsers.

    However, it is possible to do what you want in JavaScript:

    javascript:void function f(){alert(f.toString())}()
    

    That will alert the following:

    function f(){alert(f.toString())}
    

    The toString() method, when called on a function, returns a string representing the source code of the function (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString).

    Credit

    @SergeSeredenko suggested to use void.

    When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void#Immediately_Invoked_Function_Expressions