A Complete Guide to Bookmarklets

CSS-Tricks5 min read

Understanding Bookmarklets

Bookmarklets are JavaScript scripts saved as bookmarks, allowing developers to perform actions beyond merely saving web pages. They are versatile tools that can enhance productivity in web development without requiring additional software.

Creating a Basic Bookmarklet

To create a bookmarklet, write a JavaScript script and prefix it with javascript:. For example, to create a simple alert, use the following code:

javascript:(() => { alert("Hello, World!"); })();

To avoid global namespace pollution, wrap your code in an Immediately Invoked Function Expression (IIFE). URL-encode your bookmarklet to ensure compatibility across browsers.

CSS Bookmarklets

Bookmarklets can also apply CSS styles to web pages. One method is to create a <style> element:

javascript:(() => { var style = document.createElement("style"); style.innerHTML = "body{background:#000;color:rebeccapurple}"; document.head.appendChild(style); })();

For more control, use the CSSStyleSheet interface to modify styles dynamically.

Limitations and Best Practices

Be aware of Content Security Policies (CSP) that may block bookmarklet execution. Bookmarklets should be self-contained to avoid reliance on external resources. If you encounter issues with length, consider using external scripts or tools like TamperMonkey for more complex tasks. Always be cautious when using bookmarklets from unknown sources to avoid security risks.

Get your personalized feed

Trace curates the best articles, videos, and discussions based on your interests and role. Stop doom-scrolling, start learning.

Try Trace free