The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

Side effect-free bookmarklets: wrap them in an IIFE (Immediately Invoked Function Expression)

Posted by jpluimers on 2023/06/08

In Bookmarklets for Archive.is and the WayBack Machine to go to the original page, I wrote about how the Shadow DOM is used to prevent side effects between the code of the WayBack machine and the archived page.

In a similar manner, Bookmarklets can also interfere with code on the page and vice versa, for instance by using global variables.

That is why the [Wayback/Archive] A simple bookmarklet to tweet the current page – DEV Community is wrapped in a special kind of function:

javascript:(function(){
  n=getSelection().anchorNode;
  t=n.nodeType===3?n.data:n.innerText;t=''+t+'\\n\\n';
  window.open(`https://twitter.com/intent/tweet?
  text=${encodeURIComponent(t)}${document.location.href}`)
})()

This is an [Wayback/Archive] IIFE – MDN Web Docs Glossary: Definitions of Web-related terms | MDN or “Immediately Invoked Function Expression”, a mechanism coined by [Archive] Ben Alman (@cowboy) / Twitter at [Wayback/Archive] Ben Alman » Immediately-Invoked Function Expression (IIFE).

Since the variables are inside the function body, they won’t interfere with the page. The body will be immediately executed.

Related:

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.