Search code examples
javascriptbookmarklet

iife vs simple statement behavior with document.title


I was looking for a way to change the current page tab's title using a javascript bookmarklet.

I initially tried a simple statement but it was actually navigating me to a new page which contained only the title. I then found the same code but wrapped around as an iife.

Basically I am trying to understand the different between this:

javascript: document.title="title";

And this:

javascript: (function(){document.title="title";})();

Would someone kindly explain why the first statement navigates from the page and the second iife statement actually changes the title?


Solution

  • That's basically just what bookmarklets do - if the expression that follows the javascript: resolves to something other than undefined (such as a string), the current page will be replaced. So, one option to run arbitrary Javascript is to run an IIFE that doesn't return anything. More explanation available here.

    The behavior may vary across browsers.

    Another option is to use the comma operator:

    javascript: (document.title = 'www.google.com', undefined)
    

    For any code that isn't extremely trivial, you might consider using a userscript (like with Tampermonkey) instead of a bookmarklet, it'll probably be more manageable.