How I built a browser extension that translates live web elements and responsive CSS layouts into native Figma vector layers and editable auto-layouts.
Every front-end engineer knows the familiar pain of the design-to-code workflow. An entire industry of tooling exists to convert Figma frames into React components, Tailwind utility classes, and design tokens. But when you are tasked with modernizing a five-year-old enterprise dashboard, capturing a live production layout for design critique, or migrating legacy components into a fresh design system, you run into the reverse-engineering gap: code-to-Figma is broken.
Most teams resort to flat screenshots. The moment you paste a rasterized PNG into Figma, you lose everything that makes design tools useful: auto-layout rules, text layers, vector curves, border radiuses, and color swatches. Your product designer has to spend three hours manually rebuilding buttons, cards, and navigation bars just to move a modal dialog forty pixels to the left.
To solve this, I built Zcrap, an open-source browser extension that inspects any live web element, deconstructs its computed styles and box model, and serializes the DOM subtree into native Figma vector layers and editable AutoLayout components.
Building Zcrap forced me to bridge two completely different mental models: the browser's dynamic, constraint-based rendering engine and Figma's declarative, coordinate-oriented scene graph. Here is how the architecture works under the hood.
The reverse-engineering gap
The web platform was never meant to be serialized backward. A modern web page is a tree of dynamic layout contexts, cascading style rules, inherited font properties, and composited stacking layers.
When developers attempt to extract Figma elements from the web, they typically try one of three naive approaches:
- DOM snapshotting and canvas rasterization (
html2canvas): This produces bitmap images. It looks visually accurate, but you cannot edit the text, resize containers with responsive constraints, or extract vector icons. - Naive HTML-to-SVG export: Serializing a DOM subtree into an SVG
<foreignObject>or flattening layers into raw vector paths destroys layout metadata. Figma imports this as a massive, uneditable group of ungrouped strokes and clipped rectangles. - Flat absolute-positioned frames: Earlier browser extensions computed
getBoundingClientRect()for every single tag and created absolute-positioned Figma frames. While this preserves initial coordinates, the resulting Figma file is impossible to maintain. Resizing a card does not push sibling elements down, padding cannot be adjusted, and text wrapping breaks instantly.
To make imported components truly usable in a production design system, the converter must reconstruct the designer's original intent, not just the rendered pixels. If a container uses display: flex; gap: 16px; align-items: center;, Figma needs to receive an AutoLayout frame with horizontal direction, 16px item spacing, and centered counter-axis alignment.
Achieving this fidelity requires a five-stage transformation pipeline.
The five-stage transformation pipeline
Zcrap executes as a Chrome extension content script that communicates with a background worker and an accompanying Figma plugin. The extraction engine operates as an ordered, multi-pass pipeline.
+-------------------------------------------------------------------+
| 1. DOM Traversal & Pruning |
| - Recursive walk (inc. Shadow DOM) |
| - Visibility & zero-dimension filtering |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 2. Computed Style & Box-Model Extraction |
| - Flexbox / Grid to AutoLayout mapping |
| - Box-sizing & padding normalization |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 3. Semantic Naming & ARIA Analysis |
| - Tag & ARIA role heuristics |
| - Contextual text and class name synthesis |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 4. Vector & SVG Serialization |
| - Inline SVG path parsing & viewBox scaling |
| - currentColor & CSS variable resolution |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 5. Scene Graph Compilation & Memory Budgeting |
| - Delta style encoding & color normalization |
| - Chunked IPC clipboard payload |
+-------------------------------------------------------------------+
Stage 1: Deep DOM traversal, visibility filtering, and subtree pruning
The first step is collecting relevant DOM nodes without overwhelming the browser runtime. Real-world web applications are littered with non-rendering nodes: <script>, <style>, <noscript>, hidden tracking pixels, off-screen modals, and empty utility wrappers.
Zcrap traverses the selected DOM subtree recursively using a depth-first traversal that also pierces shadowRoot boundaries for Web Components:
function isNodeVisible(
element: HTMLElement,
style: CSSStyleDeclaration
): boolean {
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.visibility === "collapse" ||
parseFloat(style.opacity) === 0
) {
return false
}
// Filter out elements with zero dimensions unless they allow visible overflow
const rect = element.getBoundingClientRect()
if (rect.width === 0 && rect.height === 0) {
const hasVisibleOverflow = style.overflow === "visible"
const hasChildren = element.children.length > 0
return hasVisibleOverflow && hasChildren
}
return true
}Beyond basic visibility, Zcrap prunes redundant anonymous containers. For example, modern front-end frameworks often produce wrappers like:
<div class="transition-all">
<div class="w-full">
<button>Confirm</button>
</div>
</div>If an intermediate <div> has no background, no border, no padding, no margin, and identical dimensions to its single child, Zcrap collapses the redundant layer. This keeps the resulting Figma layer list clean and prevents deep hierarchy nesting.
Stage 2: Computed CSS and box-model computation
Once the subtree is pruned, Zcrap resolves the exact geometry and styles for each remaining node using window.getComputedStyle(element).
The core challenge is translating CSS layout mechanisms into Figma's AutoLayout specification. Figma frames support a subset of Flexbox behaviors:
| CSS Property | CSS Value | Figma AutoLayout Property |
|---|---|---|
display: flex | flex-direction: row | layoutMode: "HORIZONTAL" |
display: flex | flex-direction: column | layoutMode: "VERTICAL" |
justify-content | flex-start / start | primaryAxisAlignItems: "MIN" |
justify-content | center | primaryAxisAlignItems: "CENTER" |
justify-content | flex-end / end | primaryAxisAlignItems: "MAX" |
justify-content | space-between | primaryAxisAlignItems: "SPACE_BETWEEN" |
align-items | flex-start / start | counterAxisAlignItems: "MIN" |
align-items | center | counterAxisAlignItems: "CENTER" |
align-items | flex-end / end | counterAxisAlignItems: "MAX" |
gap | 16px | itemSpacing: 16 |
padding | 12px 24px | paddingTop: 12, paddingRight: 24, ... |
For children inside an AutoLayout frame, sizing modes must be mapped accurately:
- If a child element has
flex: 1 1 0%orwidth: 100%within a vertical stack, its horizontal sizing is set tolayoutSizingHorizontal: "FILL"(previouslylayoutGrow = 1). - If an element's dimensions match its intrinsic content, it becomes
layoutSizingHorizontal: "HUG". - If an element has an explicit pixel dimension (e.g.,
width: 320px), it receiveslayoutSizingHorizontal: "FIXED".
function mapFlexToAutoLayout(style: CSSStyleDeclaration) {
const isHorizontal = style.flexDirection.includes("row")
const primaryAlignMap: Record<
string,
"MIN" | "CENTER" | "MAX" | "SPACE_BETWEEN"
> = {
"flex-start": "MIN",
start: "MIN",
center: "CENTER",
"flex-end": "MAX",
end: "MAX",
"space-between": "SPACE_BETWEEN",
}
const counterAlignMap: Record<string, "MIN" | "CENTER" | "MAX"> = {
"flex-start": "MIN",
start: "MIN",
center: "CENTER",
"flex-end": "MAX",
end: "MAX",
}
return {
layoutMode: isHorizontal ? "HORIZONTAL" : "VERTICAL",
primaryAxisAlignItems: primaryAlignMap[style.justifyContent] ?? "MIN",
counterAxisAlignItems: counterAlignMap[style.alignItems] ?? "MIN",
itemSpacing: parseFloat(style.gap) || 0,
paddingTop: parseFloat(style.paddingTop) || 0,
paddingRight: parseFloat(style.paddingRight) || 0,
paddingBottom: parseFloat(style.paddingBottom) || 0,
paddingLeft: parseFloat(style.paddingLeft) || 0,
}
}For CSS Grid elements, Figma does not offer a direct equivalent. When Zcrap encounters a grid with single-axis repeaters (such as grid-template-columns: repeat(3, 1fr) without complex row spans), it decomposes the grid into an outer vertical AutoLayout frame containing horizontal row frames. For irregular grid layouts, it falls back to positioned frames with proportional constraints.
Stage 3: ARIA and semantic layer naming
Nothing ruins a designer's workflow faster than opening a Figma file filled with layers named Frame 1042, div, div, and Rectangle 88.
In Zcrap, I implemented a semantic heuristics engine that derives human-readable, design-system-friendly layer names using a hierarchy of cues:
- Explicit ARIA attributes: If an element declares
aria-label="Close dialog", the layer is immediately named"Button / Close dialog". - Semantic HTML tags: Elements like
<nav>,<header>,<footer>,<aside>,<button>, and<input>provide strong baseline roles. - Contextual leaf text: If a button contains the text
"Sign In", naming it"Button / Sign In"mirrors standard design system component naming conventions. - Sanitized class names: When semantic tags are absent, Zcrap inspects the element's CSS classes. Instead of copying atomic utility classes like
px-4 py-2 bg-blue-600 rounded-md, it filters for component tokens using regex patterns (/card|modal|navbar|item|avatar|badge|tab/i) or BEM naming conventions (.btn__iconbecomes"Icon").
function resolveLayerName(element: HTMLElement, textContent?: string): string {
const ariaLabel = element.getAttribute("aria-label")
if (ariaLabel) {
return `${capitalize(element.tagName.toLowerCase())} / ${ariaLabel}`
}
const role = element.getAttribute("role")
if (role) {
return capitalize(role)
}
const tagName = element.tagName.toLowerCase()
if (tagName === "button") {
const label = textContent?.trim().slice(0, 20)
return label ? `Button / ${label}` : "Button"
}
if (tagName === "nav") return "Navigation"
if (tagName === "header") return "Header"
if (tagName === "footer") return "Footer"
if (tagName === "input")
return `Input / ${element.getAttribute("placeholder") || "Text"}`
// Extract semantic hints from CSS class tokens
const classes = Array.from(element.classList)
const semanticClass = classes.find((c) =>
/^(btn|button|card|badge|modal|dialog|menu|avatar|item)/i.test(c)
)
if (semanticClass) {
return formatClassName(semanticClass)
}
return tagName
}This simple layer naming pass transforms arbitrary web code into structured Figma components that feel like they were constructed by an organized designer.
Stage 4: SVG path extraction and inline vector serialization
Modern web applications rely heavily on SVG icons from libraries like Lucide, Heroicons, or Radix Icons. Extracting an SVG requires more than just copying the <svg> node's outer HTML.
In a live DOM tree, SVG icons frequently use dynamic styles:
- Colors are defined via
fill="currentColor"orstroke="currentColor". - Dimensions may be inherited through parent CSS classes (
size-4in Tailwind). - Paths can be split across
<use>symbols or nested inside<defs>tags.
Zcrap inspects the computed color of the SVG's parent container and replaces all occurrences of currentColor with resolved hex or RGBA values. It evaluates the SVG's bounding box and viewBox coordinates, calculates any active SVG matrix transforms, and flattens nested <use> references into explicit <path> and <g> tags.
The normalized SVG XML is then packaged with its exact target width and height, ready for Figma's figma.createNodeFromSvg() parser.
Stage 5: Generating the Figma scene payload without exceeding memory limits
Once the extraction pass completes, Zcrap must serialize the node tree into a JSON structure that can be transferred to the Figma plugin.
On complex pages, serializing every computed CSS property across thousands of nodes leads to a catastrophic memory footprint. A single getComputedStyle object contains over 300 properties. Serializing a 2,500-node DOM subtree without filtering produces a JSON payload larger than 120 megabytes. This easily crashes the Chrome extension's inter-process message bus and freezes Figma's WebAssembly environment.
To maintain near-instant performance, Zcrap applies aggressive payload optimization:
- Style diffing: Only properties that deviate from browser defaults are included in the payload. If an element has no borders, the border payload is omitted entirely.
- Color normalization: CSS colors (
rgb(37, 99, 235),rgba(...),hsl(...)) are parsed into Figma's normalized 0-to-1 float format ({ r: 0.145, g: 0.388, b: 0.922, a: 1 }). - Tree compaction: Intermediate wrapper nodes that do not affect layout, background, or borders are hoisted and merged into their child nodes.
The resulting JSON payload averages under 400 kilobytes for typical web components and takes less than 80 milliseconds to parse inside the Figma plugin.
The hardest edge cases in DOM-to-canvas translation
Building a web scraper is straightforward; building an accurate layout translator is an exercise in handling endless edge cases. The following browser behaviors were the most challenging to resolve.
CSS transforms and matrix decomposition
Web elements often use CSS transforms for centering (transform: translate(-50%, -50%)), scale effects, or rotations. When reading getComputedStyle, the browser returns these as a 2D affine transformation matrix:
matrix(a, b, c, d, tx, ty)
Figma nodes do not accept arbitrary CSS transform strings. Instead, Figma frames and vector layers utilize a $2 \times 3$ affine transform matrix:
type Transform = [[number, number, number], [number, number, number]]To bridge this, Zcrap decomposes the computed CSS matrix using polar decomposition:
$$\theta = \operatorname(b, a)$$
$$s_x = \sqrt, \quad s_y = \sqrt$$
function decomposeMatrix(matrixStr: string) {
if (!matrixStr || matrixStr === "none") {
return { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 }
}
const values = matrixStr
.match(/matrix\((.+)\)/)?.[1]
.split(",")
.map(Number)
if (!values || values.length !== 6) {
return { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 }
}
const [a, b, c, d, tx, ty] = values
const rotation = Math.atan2(b, a) * (180 / Math.PI)
const scaleX = Math.hypot(a, b)
const scaleY = Math.hypot(c, d)
return { x: tx, y: ty, rotation, scaleX, scaleY }
}Because Figma AutoLayout frames do not support non-orthogonal shearing or skewing, shear components are handled by wrapping the content into an isolated group with an explicit coordinate transform.
Synthetic nodes for ::before and ::after pseudo-elements
CSS pseudo-elements (::before and ::after) are not real DOM nodes. They do not appear in element.childNodes, yet they are responsible for custom icons, decorative badges, background accents, and tooltip arrows.
To capture them, Zcrap runs an explicit check on every element:
function extractPseudoElement(
element: HTMLElement,
pseudo: "::before" | "::after"
): SyntheticNode | null {
const style = window.getComputedStyle(element, pseudo)
const content = style.getPropertyValue("content")
// If content is empty or unset, the pseudo-element does not render
if (
!content ||
content === "none" ||
(content === '""' && !style.backgroundImage && !style.backgroundColor)
) {
return null
}
const parentRect = element.getBoundingClientRect()
// Generate a virtual node with computed pseudo styles
return {
type: "SYNTHETIC_FRAME",
name: pseudo,
style,
parentRect,
}
}When a pseudo-element is active, Zcrap creates a synthetic child node and injects it into the element's child queue in the proper stacking order (::before at index 0, ::after at the end).
Asymmetric corner radii and elliptical curves
CSS allows asymmetric corner radii across all four corners, as well as elliptical radii:
border-radius: 12px 24px 8px 16px;
border-radius: 50% / 25%;Figma rectangle and frame nodes support independent corner radii (topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius), which maps cleanly to four-value CSS definitions.
However, Figma does not natively support elliptical corner radii on rectangular frames. When an element uses border-radius: 50%, Zcrap calculates the shorter axis of the element ($r = \min(\text, \text) / 2$) to produce a clean circular or pill-shaped container, preventing distortion.
Clip paths and masked bounds
Elements with overflow: hidden map directly to Figma's clipsContent = true property on frames.
However, elements styled with CSS clip-path (such as clip-path: polygon(...) or diagonal cuts) cannot be represented by simple rectangular clipping. In these scenarios, Zcrap extracts the polygon or circle coordinates, constructs a Figma vector path that acts as a mask node, and groups the masked children within a dedicated mask frame.
Font matching and typography metrics
Typography is notoriously tricky when moving from the browser to Figma:
- Missing local fonts: The browser can render any web font via
@font-faceor Google Fonts. Inside Figma, the plugin environment must explicitly callawait figma.loadFontAsync({ family, style })before setting characters on aTextNode. If that specific font is not available in Figma's font directory, the call throws an error. - Font weight mapping: CSS specifies font weights as numeric values (
font-weight: 600), whereas Figma uses style name strings ("SemiBold"). - Line height calculations: CSS supports unitless line heights (
line-height: 1.5), keywords (normal), and explicit pixels. Figma requires either{ value: 150, unit: "PERCENT" }or{ value: 24, unit: "PIXELS" }.
Zcrap maintains a font fallback and weight translation map:
const FONT_WEIGHT_MAP: Record<string, string> = {
"100": "Thin",
"200": "ExtraLight",
"300": "Light",
"400": "Regular",
"500": "Medium",
"600": "SemiBold",
"700": "Bold",
"800": "ExtraBold",
"900": "Black",
}
function resolveFigmaFont(family: string, weight: string, isItalic: boolean) {
const cleanFamily = family.split(",")[0].replace(/['"]/g, "").trim()
const weightName = FONT_WEIGHT_MAP[weight] || "Regular"
const style = isItalic ? `${weightName} Italic` : weightName
return { family: cleanFamily, style }
}If figma.loadFontAsync fails for a proprietary or uninstalled font, the plugin catches the exception and falls back to system fonts (Inter or Roboto), preserving the text content, font size, tracking, and bounding geometry.
Anatomy of the node converter: a deep code walkthrough
The following simplified module shows how Zcrap processes a DOM element and its children recursively, assembling an intermediate scene graph node that Figma can consume:
export interface FigmaIntermediateNode {
type: "FRAME" | "TEXT" | "VECTOR"
name: string
x: number
y: number
width: number
height: number
layoutMode?: "NONE" | "HORIZONTAL" | "VERTICAL"
primaryAxisAlignItems?: "MIN" | "CENTER" | "MAX" | "SPACE_BETWEEN"
counterAxisAlignItems?: "MIN" | "CENTER" | "MAX"
itemSpacing?: number
padding?: { top: number; right: number; bottom: number; left: number }
fills?: Array<{
type: "SOLID"
color: { r: number; g: number; b: number }
opacity: number
}>
strokes?: Array<{
type: "SOLID"
color: { r: number; g: number; b: number }
opacity: number
}>
strokeWeight?: number
cornerRadius?: number | [number, number, number, number]
clipsContent?: boolean
characters?: string
fontSize?: number
fontName?: { family: string; style: string }
children?: FigmaIntermediateNode[]
svgData?: string
}
export function convertElementToFigmaNode(
element: HTMLElement,
parentRect?: DOMRect
): FigmaIntermediateNode | null {
const style = window.getComputedStyle(element)
if (!isNodeVisible(element, style)) {
return null
}
const rect = element.getBoundingClientRect()
const relativeX = parentRect ? rect.left - parentRect.left : rect.left
const relativeY = parentRect ? rect.top - parentRect.top : rect.top
// Case 1: Handle inline SVG elements as vector nodes
if (element.tagName.toLowerCase() === "svg") {
return {
type: "VECTOR",
name: resolveLayerName(element),
x: relativeX,
y: relativeY,
width: rect.width,
height: rect.height,
svgData: serializeCleanSvg(element as unknown as SVGSVGElement, style),
}
}
// Case 2: Pure text node or single-text container
const directText = getDirectTextContent(element)
const isLeafText = element.children.length === 0 && directText.length > 0
if (isLeafText) {
const isItalic = style.fontStyle === "italic"
return {
type: "TEXT",
name: directText.slice(0, 24),
x: relativeX,
y: relativeY,
width: rect.width,
height: rect.height,
characters: directText,
fontSize: parseFloat(style.fontSize) || 16,
fontName: resolveFigmaFont(style.fontFamily, style.fontWeight, isItalic),
fills: [parseSolidColor(style.color)],
}
}
// Case 3: Layout container (AutoLayout frame or standard frame)
const isFlex = style.display === "flex" || style.display === "inline-flex"
const autoLayout = isFlex ? mapFlexToAutoLayout(style) : null
const node: FigmaIntermediateNode = {
type: "FRAME",
name: resolveLayerName(element, directText),
x: relativeX,
y: relativeY,
width: rect.width,
height: rect.height,
clipsContent: style.overflow === "hidden" || style.overflow === "clip",
fills: parseBackgroundFills(style.backgroundColor),
...parseBorders(style),
...parseCornerRadius(style),
...(autoLayout || { layoutMode: "NONE" }),
children: [],
}
// Process synthetic ::before pseudo-element
const beforePseudo = extractPseudoElement(element, "::before")
if (beforePseudo) {
const virtualChild = convertElementToFigmaNode(beforePseudo.element, rect)
if (virtualChild) node.children?.push(virtualChild)
}
// Recurse over real DOM children
for (const child of Array.from(element.children)) {
if (child instanceof HTMLElement) {
const childNode = convertElementToFigmaNode(child, rect)
if (childNode) {
node.children?.push(childNode)
}
}
}
// Process synthetic ::after pseudo-element
const afterPseudo = extractPseudoElement(element, "::after")
if (afterPseudo) {
const virtualChild = convertElementToFigmaNode(afterPseudo.element, rect)
if (virtualChild) node.children?.push(virtualChild)
}
return node
}On the Figma plugin side, receiving this data structure is straightforward. The plugin instantiates native nodes using Figma's Plugin API:
function buildFigmaScene(
nodeData: FigmaIntermediateNode,
parent: BaseNode & ChildrenMixin
) {
if (nodeData.type === "FRAME") {
const frame = figma.createFrame()
frame.name = nodeData.name
frame.resize(nodeData.width, nodeData.height)
if (nodeData.layoutMode !== "NONE" && nodeData.layoutMode) {
frame.layoutMode = nodeData.layoutMode
frame.primaryAxisAlignItems = nodeData.primaryAxisAlignItems ?? "MIN"
frame.counterAxisAlignItems = nodeData.counterAxisAlignItems ?? "MIN"
frame.itemSpacing = nodeData.itemSpacing ?? 0
if (nodeData.padding) {
frame.paddingTop = nodeData.padding.top
frame.paddingRight = nodeData.padding.right
frame.paddingBottom = nodeData.padding.bottom
frame.paddingLeft = nodeData.padding.left
}
}
if (nodeData.fills) frame.fills = nodeData.fills
if (nodeData.clipsContent !== undefined)
frame.clipsContent = nodeData.clipsContent
parent.appendChild(frame)
for (const childData of nodeData.children ?? []) {
buildFigmaScene(childData, frame)
}
} else if (nodeData.type === "TEXT") {
const textNode = figma.createText()
textNode.name = nodeData.name
// Load font asynchronously before applying text characters
figma.loadFontAsync(nodeData.fontName!).then(() => {
textNode.characters = nodeData.characters ?? ""
textNode.fontSize = nodeData.fontSize ?? 16
if (nodeData.fills) textNode.fills = nodeData.fills
parent.appendChild(textNode)
})
} else if (nodeData.type === "VECTOR" && nodeData.svgData) {
const vectorGroup = figma.createNodeFromSvg(nodeData.svgData)
vectorGroup.name = nodeData.name
parent.appendChild(vectorGroup)
}
}Community takeaways and reflections on browser engines
Building Zcrap gave me an immense appreciation for modern browser layout engines like Blink and WebKit.
We often take CSS for granted, complaining about centering a div or debugging specificity quirks. But when you write software that attempts to read computed browser output and reconstruct its layout rules deterministically, you realize the astonishing complexity that browsers manage on every animation frame:
- Fluid constraints vs static canvases: CSS layout engines operate on continuous constraints: intrinsic content sizing (
min-content,max-content,fit-content), flexible basis wrapping, and dynamic viewport calculations. Canvas design tools like Figma are primarily declarative coordinate systems augmented with layout constraints. Translating between them is fundamentally an exercise in lossy semantic reconstruction. - The hidden cost of DOM bloat: Deeply nested
divstructures are not just bad for web performance and accessibility; they make tools that interface with the DOM significantly more complex. Modern front-end architectures that encourage flatter, more semantic markup pay compounding dividends across developer tooling. - The power of browser extensions as reverse-engineering tools: The Chrome Extension API provides privileged access to the page runtime. Being able to inspect computed layouts, intercept stylesheet rules, and synthesize vectors in real time makes the browser an incredible platform for building productivity tools.
If you are maintaining a legacy web application, building a design system, or looking to reverse-engineer live components back into your Figma files, you can explore the source code and try the project on GitHub: abushaidislam/zcrap.