DEV Community

Cover image for Recreating Chrome's Classic: A Pixel-Perfect QR Code Generator Extension Built with WebAssembly
流浪大法师
流浪大法师

Posted on

Recreating Chrome's Classic: A Pixel-Perfect QR Code Generator Extension Built with WebAssembly

Introduction

Do you remember Chrome's built-in QR code generator feature? That sleek, elegant interface with the iconic Chrome dinosaur in the center of QR codes was once our go-to tool for sharing webpage links. Although Google removed this functionality in a later version, today I'm excited to introduce an remarkable open-source project that not only brings this feature back but achieves pixel-perfect replication in its technical implementation.

This Chrome extension, aptly named "Add QR Code Generator Icon Back To Address Bar," uses WebAssembly technology to perfectly recreate Chromium's native QR code generation algorithm, allowing us to enjoy this classic functionality once again.

Project Overview

Core Features

  • Chromium-Style QR Codes: Identical visual appearance to Chrome's native implementation
  • Chrome Dinosaur Center Pattern: The beloved Chrome dinosaur icon as the QR code's center image
  • Instant Generation: Automatically generates QR codes for the current page URL
  • Custom Text Support: Create QR codes for any text or URL
  • One-Click Copy & Download: Support for high-quality PNG image copying and downloading

Technology Stack

This project employs a modern technology stack:

{
  "Framework": "WXT - Modern web extension framework",
  "Frontend": "React 19 + TypeScript",
  "Styling": "Tailwind CSS 4.0 + Radix UI components",
  "QR Generation": "WebAssembly module",
  "Build System": "Vite + Rollup",
  "Package Manager": "pnpm"
}
Enter fullscreen mode Exit fullscreen mode

Technical Deep Dive

1. WebAssembly-Powered QR Code Generation

The project's core highlight is using a WebAssembly module to replicate Chrome's native QR code generation algorithm. Let's examine the loader implementation:

// src/lib/wasm-loader.ts
export interface WasmQRGenerator {
  QuietZone: {
    WillBeAddedByClient: number
    Included: number
  }
  CenterImage: {
    Dino: number
    None: number
  }
  ModuleStyle: {
    Circles: number    // Circular modules
    Squares: number    // Square modules
  }
  LocatorStyle: {
    Rounded: number    // Rounded locators
    Square: number     // Square locators
  }
  generate_qr_code_with_options: (
    text: string,
    moduleStyle: number,
    locatorStyle: number,
    centerImage: number,
    quietZone: number
  ) => QRCodeResult
}
Enter fullscreen mode Exit fullscreen mode

2. Precise Constant Definitions

To ensure complete consistency with Chromium, the project defines exact constants:

// src/hooks/use-qrcode.ts
const MODULE_SIZE_PIXELS = 10        // 10 pixels per module
const DINO_TILE_SIZE_PIXELS = 4      // 4 pixels for dino tiles
const LOCATOR_SIZE_MODULES = 7       // 7x7 module locators
const QUIET_ZONE_SIZE_PIXELS = MODULE_SIZE_PIXELS * 4  // 40-pixel margin
const MAX_INPUT_LENGTH = 2000        // Maximum input length
Enter fullscreen mode Exit fullscreen mode

3. Pixel-Perfect Chrome Dinosaur Replication

Most impressively, the project directly copies the dinosaur pattern's pixel data from Chromium source code:

// Dinosaur dimension definitions
const kDinoWidth = 20
const kDinoHeight = 22
const kDinoHeadHeight = 8
const kDinoBodyHeight = 14

// Dinosaur head pixel data (facing right) - Direct copy from Chromium
const kDinoHeadRight = [
  0b00000000, 0b00011111, 0b11100000,
  0b00000000, 0b00111111, 0b11110000,
  0b00000000, 0b00110111, 0b11110000,
  // ... more pixel data
]

// Dinosaur body pixel data
const kDinoBody = [
  0b10000000, 0b01111100, 0b00000000,
  0b10000001, 0b11111100, 0b00000000,
  // ... more pixel data
]
Enter fullscreen mode Exit fullscreen mode

4. Custom Hook: useQRCode

The project uses React Hook pattern to encapsulate QR code generation logic:

export const useQRCode = (): [QRCodeState, QRCodeActions] => {
  const [state, setState] = useState<QRCodeState>({
    isLoading: false,
    error: null,
    qrData: null,
    qrSize: 0,
    originalSize: 0
  })

  const generateQRCode = useCallback(async (inputText: string) => {
    // Validate input length
    if (inputText.length > MAX_INPUT_LENGTH) {
      setState(prev => ({
        ...prev,
        error: `Input is too long. Please shorten the text to ${MAX_INPUT_LENGTH} characters or less.`
      }))
      return
    }

    // Call WASM module to generate QR code
    const result = wasmModuleRef.current.generate_qr_code_with_options(
      inputText,
      wasmModuleRef.current.ModuleStyle.Circles,     // Circular data modules
      wasmModuleRef.current.LocatorStyle.Rounded,    // Rounded locators
      wasmModuleRef.current.CenterImage.Dino,        // Dinosaur center image
      wasmModuleRef.current.QuietZone.WillBeAddedByClient
    )
  }, [])

  return [state, { generateQRCode, copyQRCode, downloadQRCode, clearError }]
}
Enter fullscreen mode Exit fullscreen mode

5. Canvas Rendering: Precisely Replicating Chromium's Drawing Algorithm

Rounded Locator Drawing

const drawLocators = (
  ctx: CanvasRenderingContext2D,
  dataSize: { width: number; height: number },
  paintForeground: { color: string },
  paintBackground: { color: string },
  margin: number,
  modulePixelSize: number
) => {
  const chromiumModuleSize = 10
  const scaleFactor = modulePixelSize / chromiumModuleSize
  const radius = 10 * scaleFactor

  const drawOneLocator = (leftXModules: number, topYModules: number) => {
    // Outermost square, 7x7 modules
    let leftXPixels = leftXModules * modulePixelSize
    let topYPixels = topYModules * modulePixelSize
    let dimPixels = modulePixelSize * LOCATOR_SIZE_MODULES

    drawRoundRect(ctx, margin + leftXPixels, margin + topYPixels,
                  dimPixels, dimPixels, radius, paintForeground.color)

    // Middle square, 5x5 modules
    leftXPixels += modulePixelSize
    topYPixels += modulePixelSize
    dimPixels -= 2 * modulePixelSize

    drawRoundRect(ctx, margin + leftXPixels, margin + topYPixels,
                  dimPixels, dimPixels, radius, paintBackground.color)

    // Inner square, 3x3 modules
    leftXPixels += modulePixelSize
    topYPixels += modulePixelSize
    dimPixels -= 2 * modulePixelSize

    drawRoundRect(ctx, margin + leftXPixels, margin + topYPixels,
                  dimPixels, dimPixels, radius, paintForeground.color)
  }

  // Draw three locators: top-left, top-right, bottom-left
  drawOneLocator(0, 0)
  drawOneLocator(dataSize.width - LOCATOR_SIZE_MODULES, 0)
  drawOneLocator(0, dataSize.height - LOCATOR_SIZE_MODULES)
}
Enter fullscreen mode Exit fullscreen mode

Pixel-Level Dinosaur Drawing

const drawDinoPixelByPixel = (
  ctx: CanvasRenderingContext2D,
  destX: number,
  destY: number,
  destWidth: number,
  destHeight: number
) => {
  const scaleX = destWidth / kDinoWidth
  const scaleY = destHeight / kDinoHeight

  ctx.fillStyle = moduleColor

  const drawPixelData = (srcArray: number[], srcNumRows: number, startRow: number) => {
    for (let row = 0; row < srcNumRows; row++) {
      for (let bit = 0; bit < kDinoWidth; bit++) {
        const byteIndex = row * kDinoWidthBytes + Math.floor(bit / 8)
        const bitIndex = 7 - (bit % 8)

        if (srcArray[byteIndex] & (1 << bitIndex)) {
          const pixelX = destX + bit * scaleX
          const pixelY = destY + (startRow + row) * scaleY
          ctx.fillRect(pixelX, pixelY, scaleX, scaleY)
        }
      }
    }
  }

  // Draw dinosaur head and body
  drawPixelData(kDinoHeadRight, kDinoHeadHeight, 0)
  drawPixelData(kDinoBody, kDinoBodyHeight, kDinoHeadHeight)
}
Enter fullscreen mode Exit fullscreen mode

6. User Interface: Replicating Chrome's Design Language

The main interface component perfectly replicates Chrome's design style:

// src/popup/App.tsx
function App() {
  const [qrState, qrActions] = useQRCode()
  const [inputValue, setInputValue] = useState('')

  // Auto-retrieve current tab URL
  useEffect(() => {
    if (typeof window !== 'undefined' && window.chrome?.tabs) {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]?.url) {
          setInputValue(tabs[0].url)
        }
      })
    }
  }, [])

  // Smart filename generation
  const handleDownload = () => {
    if (qrState.qrData) {
      let filename = 'qrcode_chrome.png'
      try {
        const url = new URL(inputValue)
        if (url.hostname && !/^\d{1,3}(\.\d{1,3}){3}$/.test(url.hostname)) {
          const safeHostname = url.hostname.replace(/[^a-zA-Z0-9.-]/g, '_')
          filename = `qrcode_${safeHostname}.png`
        }
      } catch (e) {
        // Use default filename
      }
      qrActions.downloadQRCode(filename)
    }
  }

  return (
    <div className="chromium-bubble flex w-80 flex-col p-0 leading-5">
      {/* Title bar - Matching Chromium style */}
      <div className="chromium-title-bar flex min-h-10 items-center justify-between">
        <h2 className="chromium-title text-sm font-medium">Scan QR Code</h2>
        <button onClick={() => window.close()}>×</button>
      </div>

      {/* QR code display area - Exact 240px size */}
      <div className="chromium-qr-container relative flex items-center justify-center">
        <QRCodeCanvas qrData={qrData} qrSize={qrSize} originalSize={originalSize} />
      </div>

      {/* Input field - Matching Chromium's accessibility standards */}
      <Input
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        aria-label="URL or text to encode"
        placeholder="Enter URL or text"
        maxLength={2000}
      />

      {/* Button container */}
      <div className="chromium-button-container flex items-center gap-2">
        <Button onClick={handleCopy}>Copy</Button>
        <Button onClick={handleDownload}>Download</Button>
      </div>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Architecture Diagram

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   User Input    │───▶│  WASM QR         │───▶│   Canvas        │
│   URL/Text      │    │  Generation      │    │   Rendering     │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │                        │
                                ▼                        ▼
                       ┌──────────────────┐    ┌─────────────────┐
                       │  QR Code Data    │    │  Draw Locators  │
                       │  (Uint8Array)    │    │  (Rounded)      │
                       └──────────────────┘    └─────────────────┘
                                                        │
                                                        ▼
                                               ┌─────────────────┐
                                               │  Draw Data      │
                                               │  Modules        │
                                               │  (Circles)      │
                                               └─────────────────┘
                                                        │
                                                        ▼
                                               ┌─────────────────┐
                                               │  Draw Dinosaur  │
                                               │  Pattern        │
                                               │  (Pixel-perfect)│
                                               └─────────────────┘
Enter fullscreen mode Exit fullscreen mode

Installation and Usage

Install from Chrome Web Store

# Visit Chrome Web Store directly
https://chromewebstore.google.com/detail/add-qr-code-generator-ico/kacblhilkacgfnkjfodalohcnllcgmjd
Enter fullscreen mode Exit fullscreen mode

Development Environment Setup

# Clone repository
git clone https://github.com/chromium-style-qrcode/add-qrcode-generator-icon-back-to-address-bar.git
cd add-qrcode-generator-icon-back-to-address-bar

# Install dependencies (requires Node.js ≥ 24.3.0)
pnpm install

# Start development server
pnpm dev

# Production build
pnpm build

# Create distribution zip
pnpm zip
Enter fullscreen mode Exit fullscreen mode

Load into Chrome

  1. Open Chrome and navigate to chrome://extensions/
  2. Enable "Developer mode" in the top right
  3. Click "Load unpacked extension"
  4. Select the .output/chrome-mv3 folder

Technical Innovation Points

1. High-Performance WebAssembly Application

Through the WebAssembly module, the project achieves:

  • High Performance: Near-native QR code generation speed
  • Precision: Results completely consistent with Chromium algorithm
  • Cross-Platform: Runs on all WebAssembly-supported browsers

2. Pixel-Perfect Dinosaur Pattern

The project directly extracts dinosaur pattern binary data from Chromium source code, ensuring:

  • 100% Identical Visual Effect
  • Precise Pixel Alignment
  • Correct Proportional Scaling

3. Modern React Architecture

Built with React 19 and TypeScript, providing:

  • Type Safety: Complete TypeScript type definitions
  • Component Design: Reusable UI components
  • State Management: Clean Hook patterns

4. Chromium-Style User Interface

Carefully recreates Chrome's design language through Tailwind CSS:

  • Precise Dimensions: 240px QR code display area
  • Native Color Scheme: Colors consistent with Chrome
  • Accessibility Support: Complete ARIA labels and keyboard navigation

Performance Optimization Strategies

1. Debounced Input Handling

useEffect(() => {
  const timer = setTimeout(() => {
    qrActions.generateQRCode(inputValue)
  }, 300) // 300ms debounce

  return () => clearTimeout(timer)
}, [inputValue, qrActions])
Enter fullscreen mode Exit fullscreen mode

2. Canvas Optimization

// Enable high-quality scaling
ctx.imageSmoothingEnabled = false
ctx.imageSmoothingQuality = 'high'

// Use off-screen canvas for copying and downloading
const clipboardCanvas = document.createElement('canvas')
Enter fullscreen mode Exit fullscreen mode

3. Memory Management

// Timely cleanup of WASM module resources
const wasmModuleRef = useRef<WasmQRGenerator>(null)

useEffect(() => {
  return () => {
    // Cleanup resources on component unmount
    if (wasmModuleRef.current) {
      // Cleanup logic
    }
  }
}, [])
Enter fullscreen mode Exit fullscreen mode

Project Significance and Value

This project represents more than just a simple Chrome extension; it embodies:

  1. Open Source Spirit: Continuing excellent functionality through open source
  2. Technical Excellence: Extreme attention to detail and pixel-perfect replication
  3. Modern Technology Stack Application: Comprehensive use of cutting-edge technologies like WebAssembly, React 19, and TypeScript
  4. User Experience Focus: Complete accessibility support and smooth interactive experience

Conclusion

The "Add QR Code Generator Icon Back To Address Bar" project is an excellent work that combines technology with sentiment. It not only successfully recreates Chrome's classic QR code generation functionality but also achieves admirable precision in technical implementation.

Through high-performance QR code generation using WebAssembly technology, pixel-perfect dinosaur pattern replication, and modern React architecture, this project demonstrates a perfect example of how to recreate classic functionality using the latest technology stack.

For developers, this project offers rich learning value: from practical WebAssembly applications to advanced Canvas rendering techniques, from elegant React Hook design to Chrome extension development best practices.

If you also miss Chrome's classic QR code functionality or are interested in deep frontend technology applications, try this extension or dive into its source code. I believe you'll be amazed, like me, by the ingenuity of its technical implementation and its extreme pursuit of detail.


Project Repository: GitHub

Chrome Web Store: Extension Link

License: MIT License

Top comments (0)