How does Glitch refresh my app?

A small mystery presented itself the other day. I was making an app with Glitch, a web platform for building web apps. The app I was making is at toupac.glitch.me, and I had that window open while coding. In another tab with URL glitch.com/edit, I was editing the source for the app.

Every time I edited the source, my web app would refresh, showing the latest version. This was a cool feature, but how was Glitch doing it?

My first thought was “WebSocket”. But nope, nothing, and no other network activity either. This makes sense, because if my app did have WebSocket activity, it would mean Glitch injects some code into my app to make it refresh, which would be ugly.

I figured the editor and the app must be talking via some local browser magic instead. Maybe a shared worker, or service worker, shared between the tabs? But there was no evidence of these either, and this theory presented another problem: the editor is on glitch.com but the app is on glitch.me, which I think means these pages shouldn’t be allowed to talk to each other!

I got a clue when I realized that the magic only happened when I loaded my web app directly from the editor by clicking on “Show in a new window”. If I opened my app by typing in the URL directly, it wouldn’t refresh when I edited the source. There was something special about that “Show in a new window” button in the editor. It must get special powers over the window it opens, letting it refresh the window when it pleases.

I found the source in the Glitch editor. Edited for clarity, it looked like this:

const appUrl = "https://toupac.glitch.me";
let previewWindow;
function showInNewWindow() {
  previewWindow = window.open(appUrl, "_blank");
}
function updatePreview() {
  previewWindow.location = appUrl;
}

It turns out that window.open returns a WindowProxy object that you can then manipulate like a Window object. I’ve used window.open many times, but never realized it gave you magic powers over the window you open!

I’ve reproduced this functionality below. Click the button to open a new window. The new window will show the contents of the textarea. When you edit the textarea, the contents will refresh in the new window.

👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business?Read more about me or Get in touch!

More by Jim

Tagged #programming, #web. All content copyright James Fisher 2020. This post is not associated with my employer.Found an error? Edit this page.