bookmarklet.one

How to Create a Bookmarklet (Step by Step)

If you can write a few lines of JavaScript in the browser console, you can make a bookmarklet. The process is always the same: write code that works in the console, wrap it so it does not leak variables or return a value, squeeze it onto one line, encode it so it survives as a URL, and save it as a bookmark.

This guide walks through each step with a real example, then covers the problems that trip people up: comments that break the one-liner, percent signs, pages that get replaced by [object Object], and sites with strict security policies. If you just want the finished result, our maker does steps 2 through 4 for you.

Open the Bookmarklet Maker

Step 1: Write and test the code in the console

Open DevTools (F12, or Cmd+Option+I on a Mac), switch to the Console tab, and write your script there. The console runs code in the same context a bookmarklet will, so if it works there it will almost always work as a bookmarklet.

Our running example lists every image on the page that is missing an alt attribute and outlines it in red:

const missing = [...document.images].filter(img => !img.hasAttribute('alt'));
missing.forEach(img => { img.style.outline = '3px solid red'; });
alert(missing.length + ' image(s) without an alt attribute');

Paste that into the console on any news site and you will see the result immediately. Iterate here until it does what you want. Debugging is much easier in the console than in a bookmark.

Step 2: Wrap it in an IIFE

An IIFE (immediately invoked function expression) is a function that runs as soon as it is defined. Wrapping your bookmarklet in one does two things:

  • It keeps your variables private. Without it, const missing becomes a global on the page. Click the bookmarklet twice and the second run throws SyntaxError: Identifier 'missing' has already been declared. Worse, you might overwrite a variable the site depends on.
  • It stops the page from being replaced. When a javascript: URL evaluates to a value other than undefined, the browser treats that value as a new document and replaces the page with it. A function call that returns nothing evaluates to undefined, so the page stays put.
(() => {
  const missing = [...document.images].filter(img => !img.hasAttribute('alt'));
  missing.forEach(img => { img.style.outline = '3px solid red'; });
  alert(missing.length + ' image(s) without an alt attribute');
})();

A classic alternative you will see in older bookmarklets is void(...) or !function(){...}(). All of these accomplish the same thing. Arrow-function IIFEs are fine in every current browser.

Why the page turns into "[object Object]" or "true"

This is the single most common bookmarklet bug. Something like javascript:document.body.style.background='black' evaluates to the string 'black', and the browser replaces the page with the word "black". Wrap the code in an IIFE or end it with void 0 and the problem disappears:

javascript:document.body.style.background='black';void 0

Step 3: Remove comments and minify

A bookmarklet is a single line. That makes // line comments dangerous: when the newlines are removed, everything after the first // becomes part of the comment and silently never runs. Either delete comments or use block comments (/* ... */), which are safe on one line.

Make sure every statement ends with a semicolon, too. Automatic semicolon insertion depends on line breaks, and once those are gone, two statements can merge into one broken expression.

Minifying is optional for small scripts, but for anything over a few hundred characters it keeps the URL manageable. Tools like Terser or esbuild do this reliably. Minified, our example becomes:

(()=>{const e=[...document.images].filter(e=>!e.hasAttribute("alt"));e.forEach(e=>{e.style.outline="3px solid red"}),alert(e.length+" image(s) without an alt attribute")})();

Step 4: URL-encode it and add the javascript: prefix

The browser percent-decodes a bookmarklet before running it. That means characters with special meaning in URLs must be encoded, or they will be misread. The usual suspects:

CharacterEncode asWhy
%%25A bare % followed by two characters is read as an escape. width:50% can throw a URIError.
space%20Some browsers and sync services mangle raw spaces.
"%22Breaks the href attribute if you share it as a link.
#%23Can be treated as a URL fragment, cutting off the code.
newline%0AUsually better removed entirely.

The simplest correct approach is to run encodeURIComponent() on the minified code and put javascript: in front:

const code = '(()=>{ /* your minified code */ })();';
console.log('javascript:' + encodeURIComponent(code));

encodeURIComponent encodes more than strictly necessary (parentheses survive, but braces and quotes become escapes), which makes the URL longer but never wrong. Do not encode the javascript: prefix itself.

Step 5: Save it as a bookmark

There are two ways to install your new bookmarklet:

  1. Edit a bookmark manually. Bookmark any page, open the bookmark editor (right-click the bookmark, then Edit), give it a short name, and replace the URL with your javascript: string.
  2. Make a draggable link. Put the code in an href, open the HTML file, and drag the link to your bookmarks bar:
<a href="javascript:(()=>%7Balert(document.title)%7D)();">Show title</a>

Do not try to test a bookmarklet by pasting it into the address bar. Chrome and Edge strip the javascript: prefix from pasted text, Firefox ignores typed javascript: URLs by default, and Safari disables them unless a developer setting is turned on. Running it from a real bookmark is the only reliable test. See How to Add a Bookmarklet for every browser, including phones.

Step 6: Test it on a few different sites

A bookmarklet that works on your own test page can still fail elsewhere. Before you share one, try it on:

  • A plain static page (a Wikipedia article is a good baseline).
  • A big single-page app like Gmail, YouTube, or GitHub, where the DOM changes constantly.
  • A page with strict security headers. Google properties are a good stress test because many of them enforce Trusted Types.
  • The same page twice in a row, to make sure a second click does not throw or duplicate your UI.

Keep DevTools open while testing. Errors from bookmarklets show up in the console just like errors from the page.

CSP and Trusted Types gotchas

Sites can send a Content Security Policy (CSP) header that restricts what scripts may do. Browsers have mostly settled on exempting the bookmarklet's own code from the page's script-src rules, since you clicked it yourself. Firefox made that change years ago, and Chromium-based browsers generally run bookmarklets on CSP-protected pages as well. What the policy still controls is what your code does next:

  • Loading external scripts. Injecting <script src="https://your-cdn/..."> is blocked unless that host is in the page's script-src. It is also a security risk, so avoid it. Ship everything inside the bookmarklet.
  • Network requests. fetch() to another domain is governed by connect-src and by CORS. Same-origin requests, like fetching /robots.txt, are almost always fine.
  • Inline styles and style elements. A strict style-src can block a <style> element you add. Setting element.style.foo directly through the CSSOM is usually still allowed.

Trusted Types is a separate, stricter mechanism. When a page sends require-trusted-types-for 'script', assigning a plain string to innerHTML, outerHTML, or insertAdjacentHTML throws a TypeError. Plenty of older bookmarklets build their UI with innerHTML, which is why they mysteriously fail on Google Search, YouTube, or Gmail. The fix is to build elements with DOM methods:

// Breaks on Trusted Types pages:
box.innerHTML = '<b>' + title + '</b>';

// Works everywhere, and is safe from HTML injection:
const b = document.createElement('b');
b.textContent = title;
box.append(b);

Using textContent has a second benefit: page text is never interpreted as HTML, so a page title containing markup cannot inject anything into your panel. Every bookmarklet in this directory follows that rule.

A good habit for UI-heavy bookmarklets is to render the panel inside a Shadow DOM root. The page's CSS cannot leak into it, and your styles cannot break the page.

Make it toggle

Users click bookmarklets twice. Design for it. Give anything you add to the page a unique id, and if that id already exists, remove it and stop:

(() => {
  const id = 'my-outline-bm';
  const old = document.getElementById(id);
  if (old) { old.remove(); return; }
  const s = document.createElement('style');
  s.id = id;
  s.textContent = '* { outline: 1px solid rgba(255,0,0,.5) !important; }';
  document.head.append(s);
})();

That pattern turns any style-based bookmarklet into an on/off switch, and it is how CSS Outline Debugger and Dark Mode Toggle behave.

Open windows and copy text the right way

Two more patterns come up constantly:

// Open the current page in another service. Always encode the URL.
window.open('https://web.archive.org/web/*/' + encodeURIComponent(location.href), '_blank');

// Copy to clipboard. Must run directly from the click, not after a slow await.
navigator.clipboard.writeText('[' + document.title + '](' + location.href + ')');

Popup blockers and the clipboard API both require a "user gesture". A bookmarklet click counts, but only for the code that runs right away. If you await a slow fetch first and then call window.open, the browser may block it.

Share it

To share a bookmarklet, publish it as a draggable link on a web page, or share the readable source plus the encoded version so people can check what it does. Avoid sending bookmarklets through chat apps and email: they often rewrite or strip javascript: links. If someone sends you one, paste it into the Bookmarklet Decoder before installing.

Need ideas? Browse the bookmarklet directory, read how any of them work, and remix the code for your own workflow.

Frequently asked questions

Do bookmarklets need the javascript: prefix?

Yes. Without javascript: at the start, the browser treats the bookmark as a normal web address and tries to navigate to it instead of running the code.

Why does my bookmarklet replace the page with text?

Your code evaluates to a value, so the browser shows it as a new document. Wrap the code in an IIFE such as (()=>{ ... })(); or end it with void 0.

How long can a bookmarklet be?

Desktop browsers accept bookmark URLs many kilobytes long, so a few thousand characters of minified code is fine. Very large bookmarklets can be slow to sync, so keep them lean.

Can a bookmarklet load jQuery or another library?

It can inject a script tag, but many sites block external scripts through CSP and it lets the remote file change your code at any time. Modern DOM APIs make libraries unnecessary for most bookmarklets.

Why does my bookmarklet fail on Google or YouTube?

Those sites enforce Trusted Types, which makes innerHTML assignments throw. Build your UI with createElement and textContent instead.