Bookmarklet URL Encoding Guide

Master the art of properly encoding bookmarklets for maximum compatibility and reliability.

Why URL Encoding Matters

Bookmarklets are stored as URLs, which means certain characters must be encoded to work correctly. Improper encoding is one of the most common reasons bookmarklets fail. This guide will teach you everything you need to know about encoding bookmarklets properly.

πŸ”‘ Key Concepts

  • β€’ URLs have reserved characters with special meanings
  • β€’ JavaScript code often contains these reserved characters
  • β€’ Different browsers have different encoding requirements
  • β€’ Proper encoding ensures cross-browser compatibility

Characters That Need Encoding

CharacterURL EncodedUsage in JavaScriptRequired?
Space%20Between words/operatorsAlways
"%22String delimitersAlways
<%3CLess than operatorAlways
>%3EGreater than operatorAlways
#%23ID selectors, colorsAlways
%%25Modulo operatorAlways
'%27String delimitersRecommended
\n%0ALine breaksRecommended
\r%0DCarriage returnRecommended
(%28Function callsOptional
)%29Function callsOptional

Encoding Methods

Method 1: Manual Encoding

Replace characters one by one - tedious but gives full control

// Original JavaScript:
alert("Hello World!");

// Step 1: Add javascript: protocol
javascript:alert("Hello World!");

// Step 2: Replace spaces with %20
javascript:alert("Hello%20World!");

// Step 3: Replace quotes with %22
javascript:alert(%22Hello%20World!%22);

Method 2: Using encodeURIComponent()

JavaScript's built-in encoding function

// In browser console:
var code = 'alert("Hello World!");';
var encoded = 'javascript:' + encodeURIComponent(code);
console.log(encoded);
// Output: javascript:alert(%22Hello%20World!%22)%3B

// Note: This over-encodes some characters like ( and )

Method 3: Custom Encoding Function

Encode only what's necessary for better readability

function encodeBookmarklet(code) {
  // Remove comments and extra whitespace
  code = code.replace(/\/\/.*$/gm, '').replace(/\s+/g, ' ').trim();
  
  // Encode only necessary characters
  var encoded = code
    .replace(/%/g, '%25')  // Must be first!
    .replace(/ /g, '%20')
    .replace(/"/g, '%22')
    .replace(/</g, '%3C')
    .replace(/>/g, '%3E')
    .replace(/#/g, '%23')
    .replace(/\n/g, '%0A')
    .replace(/\r/g, '%0D');
    
  return 'javascript:' + encoded;
}

Common Encoding Pitfalls

❌ Pitfall 1: Double Encoding

Encoding an already encoded string breaks the bookmarklet

// Wrong: Encoding %20 again becomes %2520
javascript:alert(%2522Hello%2520World!%2522);

// Correct: Encode only once
javascript:alert(%22Hello%20World!%22);

❌ Pitfall 2: Forgetting the Percent Sign

The % character itself needs encoding when used in code

// Wrong: Modulo operator not encoded
javascript:var%20remainder%20=%20total%20%%2010;

// Correct: % encoded as %25
javascript:var%20remainder%20=%20total%20%25%2010;

❌ Pitfall 3: Mixed Quote Types

Inconsistent quote encoding causes syntax errors

// Wrong: Mixed encoded and unencoded quotes
javascript:alert(%22Hello') + alert('World%22);

// Correct: Consistent encoding
javascript:alert(%22Hello%22)%20+%20alert(%22World%22);

Browser-Specific Considerations

🌐 Chrome/Edge

  • β€’ Handles most characters without encoding
  • β€’ Automatically encodes spaces to %20
  • β€’ Maximum URL length: 2MB
  • β€’ Supports modern JavaScript syntax

🦊 Firefox

  • β€’ More strict about encoding
  • β€’ Requires proper quote encoding
  • β€’ Maximum URL length: 65,536 characters
  • β€’ May strip certain characters

🧭 Safari

  • β€’ Very strict encoding requirements
  • β€’ Limited URL length support
  • β€’ May require additional escaping
  • β€’ Test thoroughly on Safari

πŸ“± Mobile Browsers

  • β€’ Often have shorter URL limits
  • β€’ May strip javascript: protocol
  • β€’ Require minimal encoding
  • β€’ Test on actual devices

Advanced Encoding Techniques

πŸ—œοΈ Compression Techniques

Minimize bookmarklet size while maintaining readability

// Original: 147 characters
javascript:(function() {
  var elements = document.getElementsByTagName('a');
  for(var i = 0; i < elements.length; i++) {
    elements[i].style.color = 'red';
  }
})();

// Minified: 90 characters
javascript:(d=>{for(e of d.querySelectorAll('a'))e.style.color='red'})(document);

// With encoding: 94 characters  
javascript:(d=%3E%7Bfor(e%20of%20d.querySelectorAll('a'))e.style.color='red'%7D)(document);

πŸ”€ Unicode Encoding

Handle international characters and emojis

// Unicode characters need special handling
var text = "Hello δΈ–η•Œ 🌍";

// Using escape sequences
javascript:alert("Hello%20\u4E16\u754C%20\uD83C\uDF0D");

// Using encodeURIComponent for safety
javascript:alert(decodeURIComponent("%E4%B8%96%E7%95%8C"));

πŸ“¦ Base64 Encoding

Alternative encoding for complex bookmarklets

// Encode complex code as Base64
var code = "alert('Complex code with "quotes" and special chars');";
var base64 = btoa(code);

// Create self-decoding bookmarklet
javascript:eval(atob("YWxlcnQoJ0NvbXBsZXggY29kZSB3aXRoICJxdW90ZXMiIGFuZCBzcGVjaWFsIGNoYXJzJyk7"));

// Note: Increases size but handles all characters

Testing Your Encoded Bookmarklet

βœ… Testing Checklist

  1. Test in browser console first (without encoding)
  2. Encode using your chosen method
  3. Create bookmarklet in one browser
  4. Test functionality thoroughly
  5. Export and import to other browsers
  6. Test on different websites
  7. Verify on mobile devices

Encoding Tools and Utilities

πŸ› οΈ Bookmarklet Encoder Tool

Paste this into your console to create an encoding helper

// Bookmarklet Encoding Helper
function createBookmarklet(code, minify = true) {
  // Remove comments
  code = code.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
  
  // Minify if requested
  if(minify) {
    code = code
      .replace(/\s+/g, ' ')
      .replace(/\s*([{}()\[\];,:<>+\-*\/=!?&|~^%])/g, '$1')
      .replace(/([{}()\[\];,:<>+\-*\/=!?&|~^%])\s*/g, '$1')
      .trim();
  }
  
  // Smart encoding - only what's necessary
  var encoded = code
    .replace(/%/g, '%25')
    .replace(/ /g, '%20')
    .replace(/"/g, '%22')
    .replace(/</g, '%3C')
    .replace(/>/g, '%3E')
    .replace(/#/g, '%23');
    
  var bookmarklet = 'javascript:' + encoded;
  
  console.log('Original length:', code.length);
  console.log('Encoded length:', bookmarklet.length);
  console.log('Bookmarklet:', bookmarklet);
  
  // Test decoding
  try {
    var decoded = decodeURIComponent(encoded.replace(/^javascript:/, ''));
    console.log('Decode test:', decoded === code ? 'βœ“ Passed' : 'βœ— Failed');
  } catch(e) {
    console.error('Decode error:', e);
  }
  
  return bookmarklet;
}

// Usage:
createBookmarklet(`
  (function() {
    alert("Hello World!");
  })();
`);

Best Practices Summary

βœ… Do's

  • β€’ Always test before encoding
  • β€’ Use consistent encoding method
  • β€’ Encode % sign first (%25)
  • β€’ Test across browsers
  • β€’ Keep bookmarklets concise
  • β€’ Document encoding method used

❌ Don'ts

  • β€’ Don't double-encode
  • β€’ Don't mix encoding methods
  • β€’ Don't forget browser limits
  • β€’ Don't over-encode unnecessarily
  • β€’ Don't skip testing
  • β€’ Don't ignore error messages

Master Encoding

With proper encoding, your bookmarklets will work reliably across all browsers. Use our generator for automatic encoding or apply these techniques manually.