WebGL Context Lost in a Browser Game: Detect and Restore
WebGL context lost means the browser has taken your game's GPU context away, with every buffer, texture, shader and framebuffer in it. To survive it, call preventDefault() in a webglcontextlost listener, stop drawing, and rebuild everything from CPU copies when webglcontextrestored fires. I tested that on 2026-10-13 with a small WebGL2 game in Chrome 155 and Edge 155 on Windows 11, first with WEBGL_lose_context, then by crashing each browser's GPU process for real. After the first crash both browsers gave the context back on their own in about a second. After a second crash within two minutes they refused the site with "Web page caused context loss and was blocked", and once the GPU process had died three times in a session, WebGL was off for every site until the browser restarted.
The Results in One Table
One run per row, 2026-10-13 (UTC), on the real GPU of an XNDR test machine (AMD Radeon 8060S, ANGLE on Direct3D 11). Restore times end at webglcontextrestored and start at the lost event after a crash, or at the restoreContext() call in a simulation.
test Chrome 155 Edge 155
loseContext(), no restoreContext() stays lost (3 s) stays lost (3 s)
restoreContext() after the lost event restored in 56 ms restored in 59 ms
restoreContext() inside the handler ignored ignored
canvas without preventDefault() never restored never restored
1st GPU process crash restored in 1.09 s restored in 1.34 s
same game, hidden tab, other host restored in 1.10 s restored in 1.35 s
three.js r186 page restored itself restored itself
new context afterwards works works
2nd crash (36 s / 25 s later) never restored never restored
new context, same two hosts "was blocked" "was blocked"
new context, a third host GL_VENDOR = Disabled GL_VENDOR = Disabled
page reload no WebGL2 no WebGL2
tab hidden for 33 s / 14 s no loss, no frames no loss, no frames
40 contexts in one page oldest 24 lost oldest 24 lost
The second crash hit harder than it would on a normal desktop: headless Chrome and Edge had already restarted their GPU process once at launch (see the setup).
What Takes a WebGL Context Away
A WebGL context lives in the browser's GPU process, not in your page. A GPU process crash, or a lost Direct3D device that makes the browser restart that process, takes every context in every tab with it. The browser also takes contexts away on purpose when a page opens too many (below).
A hidden tab was not a cause. With the game in a background tab for 33 s in Chrome and 14 s in Edge, the context stayed, requestAnimationFrame stopped calling the loop, and drawing resumed when the tab came back.
The Setup
- Windows 11 Pro, AMD Radeon 8060S with driver 32.0.31041.1004, Node 25.2.1.
- The installed Chrome 155.0.8059.40 and Edge 155.0.4283.45, each on a new test profile, headless (
--headless=new), driven over the Chrome DevTools Protocol. - Every run's
UNMASKED_RENDERER_WEBGLwas "ANGLE (AMD, AMD Radeon(TM) 8060S Graphics (0x00001586) Direct3D11 vs_5_0 ps_5_0, D3D11)". No SwiftShader: the crashes hit a GPU process driving the real device. - Test pages on
localhost,127.0.0.1and[::1]. Chromium blocks by host, so that made three "sites". - At most six crash attempts across both browsers, each followed by a check of the Windows System log for display driver events. There were none.
One headless quirk matters. At launch both browsers logged "DCompositionCreateDevice3 failed: Access is denied", then "Restarting GPU process due to unrecoverable error. Context was lost." So each session began with one GPU process exit already counted. I read that log on edge://gpu in the Edge session I crashed, and on chrome://gpu in a later Chrome launch.
Step 1: Detect the Loss
Three things tell you the context is gone: the webglcontextlost event, gl.isContextLost(), and the first gl.getError() after the loss, which returns CONTEXT_LOST_WEBGL. Build on the event. isContextLost() was true the moment I called loseContext(); the event followed 11 to 12 ms later, as a queued task. In a real crash every context in the browser got its event within a millisecond or two, hidden tabs included.
statusMessage was empty in every case, so the event will not tell you why. One line decides whether the context comes back: event.preventDefault(). A second canvas on my page listened without calling it and was never restored, after a simulated loss or a real crash. restoreContext() on it only logged "WebGL: INVALID_OPERATION: restoreContext: context restoration not allowed".
Step 2: Keep a CPU Copy of Everything the GPU Needs
A restored context is empty. The gl object is the same JavaScript object, but nothing you created on it survives, so the game must be able to build its whole GPU side again at any time. This is the complete game I tested: a sprite bouncing in a 160x90 frame scaled up to the canvas. The page needs a 640x360 canvas with the id game and an empty, hidden div with the id notice.
// game.js: a small WebGL2 game loop that survives a lost context.
// Everything the GPU needs is kept on the CPU, so the GPU side can be rebuilt at any time.
const canvas = document.getElementById('game');
const notice = document.getElementById('notice');
const LOW_W = 160; // the game draws at 160x90 and scales that up to the canvas
const LOW_H = 90;
const VERTEX = `#version 300 es
in vec2 a_pos;
uniform vec2 u_offset;
out vec2 v_uv;
void main() {
v_uv = a_pos * 0.5 + 0.5;
gl_Position = vec4(a_pos * 0.15 + u_offset, 0.0, 1.0);
}`;
const FRAGMENT = `#version 300 es
precision mediump float;
in vec2 v_uv;
uniform sampler2D u_sprite;
out vec4 color;
void main() {
color = texture(u_sprite, v_uv);
}`;
const QUAD = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
const SPRITE = checker(8);
const state = { x: 0, y: 0, vx: 0.5, vy: 0.35, bounces: 0 }; // game state never lives in GL
const stats = { lost: 0, restored: 0, builds: 0, framesDrawn: 0, framesWhileLost: 0 };
let gpu = null; // the WebGL objects of the current context; null while it is lost
let giveUp = null;
function checker(size) {
const px = new Uint8Array(size * size * 4);
for (let i = 0; i < size * size; i++) {
const on = (i % size + Math.floor(i / size)) % 2 === 0;
px.set(on ? [255, 200, 0, 255] : [40, 40, 200, 255], i * 4);
}
return px;
}
function compile(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) throw new Error(gl.getShaderInfoLog(shader));
return shader;
}
// Builds every GPU object from the CPU copies. Runs at start and after every restore.
function createGpu(gl) {
const program = gl.createProgram();
gl.attachShader(program, compile(gl, gl.VERTEX_SHADER, VERTEX));
gl.attachShader(program, compile(gl, gl.FRAGMENT_SHADER, FRAGMENT));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS) && !gl.isContextLost()) throw new Error(gl.getProgramInfoLog(program));
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, QUAD, gl.STATIC_DRAW);
const aPos = gl.getAttribLocation(program, 'a_pos');
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
const sprite = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, sprite);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 8, 8, 0, gl.RGBA, gl.UNSIGNED_BYTE, SPRITE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
const fbo = gl.createFramebuffer(); // the low-resolution frame
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
const color = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, color);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA8, LOW_W, LOW_H);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, color);
gl.clearColor(0.05, 0.05, 0.08, 1); // global state is reset with the context, so set it here too
stats.builds++;
return { program, vao, sprite, fbo, uOffset: gl.getUniformLocation(program, 'u_offset') };
}
function update(dt) {
state.x += state.vx * dt;
state.y += state.vy * dt;
if (Math.abs(state.x) > 0.85) { state.vx = -state.vx; state.x = Math.sign(state.x) * 0.85; state.bounces++; }
if (Math.abs(state.y) > 0.85) { state.vy = -state.vy; state.y = Math.sign(state.y) * 0.85; state.bounces++; }
}
function draw(gl) {
gl.bindFramebuffer(gl.FRAMEBUFFER, gpu.fbo);
gl.viewport(0, 0, LOW_W, LOW_H);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(gpu.program);
gl.bindVertexArray(gpu.vao);
gl.bindTexture(gl.TEXTURE_2D, gpu.sprite);
gl.uniform2f(gpu.uOffset, state.x, state.y);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, gpu.fbo); // scale up to the canvas, pixel art style
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
gl.blitFramebuffer(0, 0, LOW_W, LOW_H, 0, 0, canvas.width, canvas.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
stats.framesDrawn++;
}
function showNotice(text, offerReload) {
notice.textContent = text;
if (offerReload) {
const button = document.createElement('button');
button.textContent = 'Reload';
button.onclick = () => location.reload();
notice.append(' ', button);
}
notice.hidden = false;
}
const gl = canvas.getContext('webgl2', { antialias: false });
canvas.addEventListener('webglcontextlost', (event) => {
event.preventDefault(); // without this the browser never restores the context
gpu = null; // every object from the old context is dead now
stats.lost++;
showNotice('Graphics were reset. Restoring...');
giveUp = setTimeout(() => showNotice('The graphics could not be restored.', true), 10000);
});
canvas.addEventListener('webglcontextrestored', () => {
clearTimeout(giveUp);
gpu = createGpu(gl); // same gl object, a new context behind it
stats.restored++;
notice.hidden = true;
});
let last = performance.now();
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (!gpu) { // lost: keep the loop alive, but do not simulate or draw
stats.framesWhileLost++;
return;
}
update(dt);
draw(gl);
}
if (gl) {
gpu = createGpu(gl);
requestAnimationFrame(frame);
} else {
showNotice('WebGL2 could not start here.', true);
}
window.game = { state, stats }; // read by my test driver
The design is one function, createGpu(), that builds every GPU object from data the page still holds: shader sources as strings, the quad as a Float32Array, the sprite as a Uint8Array. Game state is plain JavaScript, so a loss costs the player a second of screen, not their position. antialias: false keeps the default framebuffer single-sampled, which the final blit needs.
My test read every canvas pixel right after a frame, before each loss and after each restore, and sorted them by colour. The counts matched: background, yellow and blue only, and NO_ERROR.
What Dies With the Context
- Buffers, vertex arrays, textures, renderbuffers, framebuffers. A texture created before the loss answered
gl.isTexture()withfalseafterwards, and binding it gave "WebGL: INVALID_OPERATION: bindTexture: object does not belong to this context". - Shaders, programs and uniform locations. Look the locations up again.
- Extensions. With
EXT_color_buffer_floatenabled before the loss, a 16-bit float render target worked. After the restore it failed with "INVALID_ENUM: renderbufferStorage: EXT_color_buffer_float/EXT_color_buffer_half_float not enabled" until I called getExtension()again, which returned a new object. - Global state. The new context starts with defaults, which is why
createGpu()sets the clear colour. - Whatever you rendered to the canvas or a framebuffer. Draw it again.
One survivor: the WEBGL_lose_context object I fetched before the first loss still worked for a second cycle.
Step 3: Keep the Loop Running While Lost
requestAnimationFrame keeps firing on a lost context. During a three-second simulated loss my loop ran 181 times and drew nothing; during the real crashes it ran 55 times in Chrome and 54 in Edge before the restore. Keep requesting frames, skip drawing, pause the simulation, and clamp the frame delta (0.1 s here) so the first frame back does not move the sprite through a wall.
Step 4: Simulate It With WEBGL_lose_context
loseContext() on the WEBGL_lose_context extension loses the context and fires the event, but unlike a real loss it does not come back by itself: nothing in three seconds. After restoreContext(), webglcontextrestored fired 56 ms later in Chrome, 59 ms in Edge, and 11 ms on a second cycle.
Timing matters. A canvas that called restoreContext() inside its lost handler, right after preventDefault(), stayed lost. In the Chromium source the "restore allowed" flag is set only after the event has been dispatched with its default prevented, so the handler is too early. A later call restored it in 11 to 12 ms. These are the probe lines that checked the stale texture:
const stale = { isTexture: gl.isTexture(oldTexture) };
gl.bindTexture(gl.TEXTURE_2D, oldTexture);
stale.bindError = errName(gl.getError());
Want more like this?
New posts in your inbox, a few a month.
What a Real GPU Process Crash Did
Getting the Crash to Happen
Chrome's debug URL for this is chrome://gpucrash, Edge's is edge://gpucrash. It failed first: opening it as a new tab over CDP did nothing, nor did Page.navigate with transitionType: 'typed'. The GPU process kept its process ID. Chromium acts on these URLs only for a navigation flagged "from address bar", so typing it works and a script opening it does not. Over CDP that flag is the address_bar transition type:
const { targetId } = await send('Target.createTarget', { url: 'about:blank', background: true });
const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true });
await send('Page.navigate', { url: CRASH_URL, transitionType: 'address_bar' }, sessionId).catch((e) => log('crash-navigate-error', { error: e.message }));
Then the GPU process got a new process ID each time and every page logged "WebGL: CONTEXT_LOST_WEBGL: loseContext: context lost". The two failed attempts counted toward my six, leaving two real crashes per browser.
The First Crash: Back in About a Second
Open were the game on localhost in front, the same game on 127.0.0.1 in a background tab, and a three.js page. All lost their contexts at once. Without any call from me, Chrome restored the game after 1.09 s and Edge after 1.34 s. The background tab followed within 10 ms, as did a second canvas that also called preventDefault(); the one that did not stayed lost. The game drew the same pixels as before, and new contexts worked on both hosts. In the Chromium source a real loss makes its first restore attempt one second after the lost event, which fits.
The Second Crash: Blocked, Then No WebGL at All
The second crash came 36 s later in Chrome and 25 s later in Edge, and nothing came back. The game showed its "could not be restored" notice after ten seconds; in Edge every context was still lost more than two minutes later. A new context on localhost or 127.0.0.1 fired webglcontextcreationerror with "Web page caused context loss and was blocked". On the third host, which had never lost a context, it failed differently:
Could not create a WebGL context, VENDOR = 0xffff, DEVICE = 0xffff, GL_VENDOR = Disabled, GL_RENDERER = Disabled, Sandboxed = yes, Optimus = no, AMD switchable = no, Reset notification strategy = 0x0000, ErrorMessage = BindToCurrentSequence failed: .
edge://gpu listed "WebGL: Disabled" and the rest as "Software only". A reload did not help in either browser: getContext('webgl2') returned null. Only a new browser session reported WebGL as hardware accelerated again.
What the Chromium Source Says
Two mechanisms explain this. I read both in the Chromium source at tag 155.0.8059.40, the version I tested.
- Per-site blocking. When the GPU process dies, gpu_host_impl.cc records a loss for every URL with a live WebGL context. gpu_data_manager_impl_private.cc keys them by host, allows one loss per host ("Allow one context loss per domain, so block if there are two or more"), blocks every host after more than two separate loss events, and forgets each record after two minutes. A blocked page's restore attempt does not reschedule itself, so that context stays lost even after the two minutes.
- The crash limit. gpu_process_host.cc allows three GPU process crashes on Windows desktop, forgives one every five minutes, then falls back to the next GPU mode. With the headless restart at launch, my second crash was the third, and WebGL went to "Disabled".
A normal desktop session should take one more crash before that fallback. I did not run that, and the fallback hid the two-minute expiry. What the runs show: a second loss on a site within two minutes was blocked in both browsers.
three.js: What It Restores and What It Cannot
I tested three.js r186 (npm three 0.186.1) from a local copy. Its WebGLRenderer calls preventDefault() on the lost event, skips rendering while lost, and rebuilds its internal state on restore, so geometry, materials and textures are uploaded again from the JavaScript objects. That matches what Mugen87, the second most active committer to three.js, wrote in a 2021 forum thread.
It worked in both browsers, after forceContextLoss() and forceContextRestore() and after the first real crash. A DataTexture came back exactly. A texture from an ImageBitmap I had closed after the first frame to save memory came back black, with "WebGL: INVALID_VALUE: texSubImage2D: The source data has been detached." three.js can only upload what you still hold.
One current guide says three.js handles loss automatically "since v0.155 if you opt-in via renderer.debug.checkShaderErrors". I found no support for that: the r155 release notes mention neither, and in r186 checkShaderErrors only controls shader compile and link error checks.
Too Many Contexts
A page creating 40 small WebGL2 contexts, with two other WebGL pages open in the browser, lost its oldest context when it created the 17th, logging "WARNING: Too many active WebGL contexts. Oldest context will be lost.", and one more per new context: 24 of 40. None came back, though each called preventDefault(): Chromium restores an evicted context only when another one is destroyed. Reuse one context for menus, minimaps and previews.
What to Show the Player
The game shows "Graphics were reset. Restoring..." and gives up after ten seconds with a Reload button, generous next to the one-second restores I measured. By the source, a site blocked for repeated losses gets WebGL back on a reload once its two-minute window has passed; I did not see that run. After the browser has turned WebGL off, a reload ends in "WebGL2 could not start here.", so tell the player to restart the browser. Save the game state on loss, so either costs nothing.
If you want a browser game tested like this before launch, that is the web development work on our services page. The work page lists Edge Leaderboard, an API for browser games, and the leaderboard anti-cheat post covers that server side.
What I Did Not Test
- Firefox and Safari were not tested, on any platform. iOS was not tested, and neither was Android or any other mobile browser.
- A headed browser. All runs were headless on the real GPU, with the launch-time GPU restart described above.
- A driver reset (TDR) or driver update. I only crashed the browser's GPU process through its own debug URL. The System log showed no display driver events.
- The two-minute block expiry and the five-minute crash forgiveness: source only.
- One thing I cannot explain: in the first Edge launch, my page's very first context got "was blocked" before that page had lost anything. About 90 seconds later the same host worked. Chrome never did this.
FAQ
What does "WebGL context lost" mean?
The browser has taken the GPU context of a canvas away, for example because the GPU process crashed or was reset, or because a page created too many contexts. Every buffer, texture, shader and framebuffer in it is gone. If the page called preventDefault() on webglcontextlost, the browser may restore an empty context and fire webglcontextrestored.
Why does webglcontextrestored never fire?
In my tests, for three reasons: the canvas did not call preventDefault() on the lost event, restoreContext() was called inside the lost handler instead of after it, or the site had lost its context twice within two minutes and Chrome and Edge blocked it with "Web page caused context loss and was blocked".
Does reloading the page fix a lost WebGL context?
After one GPU process crash it is not needed: Chrome and Edge restored the context on their own in 1.09 and 1.34 seconds. After the GPU process died three times in one session, a reload did not help and WebGL stayed disabled for every site until the browser was restarted.
Does three.js restore a lost WebGL context automatically?
Yes for its own state. In r186 the renderer calls preventDefault() and rebuilds its internals on restore, and a DataTexture came back exactly in Chrome and Edge. Anything whose source you dropped, such as a closed ImageBitmap, came back black.
How do I test WebGL context loss?
Call loseContext() on the WEBGL_lose_context extension, wait for the lost event, then call restoreContext(). For a real GPU process crash, type chrome://gpucrash or edge://gpucrash into the address bar of a test browser. Opened by a script, it did nothing.
Related Articles
- Cloudflare Workers Leaderboard API with Anti-Cheat
- Prompt Injection-Safe AI Image Generation with Templates
- Diagnosing Windows with Claude Code
- XNDR services: web apps and browser games, tested before launch.
Liked this one? Get the next in your inbox.
New posts and the odd product note, a few emails a month. Easy to leave.