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:
- [Wayback/Archive] “Tweet this page” bookmarklet | Christian Heilmann
- [Wayback/Archive] codepo8/tweet-this: A bookmarklet to tweet the current document, highlight text as the tweet.
- [Wayback/Archive] Tweet this
–jeroen






Leave a comment