Search code examples
visual-studio-codeliveserver

How does the VS Code Live Server extension refresh the page?


There is this extension in VS Code marketeplace which is called Live Server. Basically what it does is that it starts listening on some port (5500) on localhost and serves the file opened in VS Code on that server. The interesting part about live server is that it refreshes the page after any of the file in editor gets updated (saved).

I would like to know how this is possible. I know about selenium but this is not it. I want to know how this extension reloads a tab in chrome. (or other browsers)


Solution

  • It uses websocket communications.

    On the server-side (VS Code side), there is a function called handleChange registered to handle events (namely change, add, unlink, addDir, unlinkDir, and ready):

    function handleChange(changePath) {
        var cssChange = path.extname(changePath) === ".css";
        ...
        clients.forEach(function (ws) {
            if (ws)
                ws.send((cssChange && !fullReload) ? 'refreshcss' : 'reload');
        });
    }
    ...
    LiveServer.watcher
        .on("change", handleChange)
        .on("add", handleChange)
        .on("unlink", handleChange)
        .on("addDir", handleChange)
        .on("unlinkDir", handleChange)
        .on("ready", function () {
            if (LiveServer.logLevel >= 1)
                console.log("Ready for changes".cyan);
            if (callback) {
                callback();
            }
        })
        .on("error", function (err) {
            console.log("ERROR:".red, err);
        });
    

    On the client-side (browser side), the extension injects HTML into the served page, which contains the following:

    socket.onmessage = function (msg) {
        if (msg.data == 'reload') window.location.reload();
        else if (msg.data == 'refreshcss') refreshCSS();
    };
    

    If you're interested, the definition of refreshCSS can be found just above that code.

    Concerning the meaning of the CSS behaviour (it's an optimization so no page reload needs to be done for CSS-only changes), see the settings docs, which state:

    • liveServer.settings.fullReload: : By Default Live Server inject CSS changes without full reloading of browser. You can change this behavior by making this setting as true.

      • Default: false