127
votes

I'm editing an HTML file in Vim and I want the browser to refresh whenever the file underneath changes.

Is there a plugin for Google Chrome that will listen for changes to the file and auto refresh the page every time I save a change to the file? I know there's XRefresh for Firefox but I could not get XRefresh to run at all.

How hard would it be to write a script to do this myself?

26
After looking for some time for works everywhere solution I coded my own: alexshulzhenko.ru/web-development-autorefresh-page-on-changesTebe
I also code my own: Live Reload for Chrome and Firefox: github.com/blaise-io/live-reload#readme. Repeat the host URL in the source file URL field of the addon to monitor itself.Blaise
Great extension, @Blaise. But why is there a minimum 0.5 second minimum for the reloading. Why not 0.1 seconds to make it more responsive?Jay
@Jay Because monitoring isn't cheap, your server would have to generate a response every 0.1s and it would need to generate a hash of the static file every 0.1s. But you can probably edit the form using developer tools to allow < 0.5s.Blaise

26 Answers

114
votes

Pure JavaScript solution!

Live.js

Just add the following to your <head>:

<script type="text/javascript" src="https://livejs.com/live.js"></script>

How? Just include Live.js and it will monitor the current page including local CSS and Javascript by sending consecutive HEAD requests to the server. Changes to CSS will be applied dynamically and HTML or Javascript changes will reload the page. Try it!

Where? Live.js works in Firefox, Chrome, Safari, Opera and IE6+ until proven otherwise. Live.js is independent of the development framework or language you use, whether it be Ruby, Handcraft, Python, Django, NET, Java, Php, Drupal, Joomla or what-have-you.

I copied this answer almost verbatim from here, because I think it's easier and more general than the currently accepted answer here.

25
votes

With the addition of a single meta tag into your document, you can instruct the browser to automatically reload at a provided interval:

<meta http-equiv="refresh" content="3" >

Placed within the head tag of your document, this meta tag will instruct the browser to refresh every three seconds.

24
votes

Handy Bash one-liner for OS X, assuming that you have installed fswatch (brew install fswatch). It watches an arbitrary path/file and refreshes the active Chrome tab when there are changes:

fswatch -o ~/path/to/watch | xargs -n1 -I {} osascript -e 'tell application "Google Chrome" to tell the active tab of its first window to reload'

See more about fswatch here: https://stackoverflow.com/a/13807906/3510611

23
votes

I assume you're not on OSX? Otherwise you could do something like this with applescript:

http://brettterpstra.com/watch-for-file-changes-and-refresh-your-browser-automatically/

There is also a plugin for chrome called "auto refresh plus" where you can specify a reload every x seconds:

https://chrome.google.com/webstore/detail/auto-refresh-plus/oilipfekkmncanaajkapbpancpelijih?hl=en

23
votes

Update: Tincr is dead.

Tincr is a Chrome extension that will refresh the page whenever the file underneath changes.

19
votes

I know this is an old question but in case it helps someone, there is a reload npm package that solves it.

In case that you are not running it on a server or have received the error Live.js doesn't support the file protocol. It needs http.

Just install it:

npm install reload -g

and then at your index.html directory, run:

reload -b

It will start a server that will refresh every time you save your changes.

There are many other options in case you're running it on the server or anything else. Check the reference for more details!

11
votes

Use Gulp to watch the files and Browsersync to reload the browser.

The steps are:

In the command line execute

npm install --save-dev gulp browser-sync

Create gulpfile.js with the following contents:

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: "./"
    }
  });

  gulp.watch("*.html").on("change", reload);
});

Run

gulp serve

Edit HTML, save and see your browser reload. The magic is done through on-the-fly injection of special tag into your HTML files.

10
votes

http://livereload.com/ - native app for OS X, Alpha version for Windows. Open sourced at https://github.com/livereload/LiveReload2

5
votes

If you are on GNU/Linux, you can use a pretty cool browser called Falkon. It's based on the Qt WebEngine. It's just like Firefox or Chromium - except, it auto refreshes the page when a file is updated. The auto refresh doesn't matter much whether you use vim, nano, or atom, vscode, brackets, geany, mousepad etc.

On Arch Linux, you can install Falkon pretty easily:

sudo pacman -S falkon

Here's the snap package.

3
votes

There is a java app for os x and Chrome called Refreschro. It will monitor a given set of files on the local file system and reload Chrome when a change is detected:

http://neromi.com/refreschro/

3
votes

Following couple of lines can do the trick:

var bfr = '';
setInterval(function () {
    fetch(window.location).then((response) => {
        return response.text();
    }).then(r => {
        if (bfr != '' && bfr != r) {
            window.location.reload();
        }
        else {
            bfr = r;
        }
    });
}, 1000);

This compares current response text with previously buffered response text after every second and will reload the page if there are any change in source code. You don't need any heavy duty plugins if you are just developing light weight pages.

2
votes

This works for me (in Ubuntu):

#!/bin/bash
#
# Watches the folder or files passed as arguments to the script and when it
# detects a change it automatically refreshes the current selected Chrome tab or
# window.
#
# Usage:
# ./chrome-refresher.sh /folder/to/watch

TIME_FORMAT='%F %H:%M'
OUTPUT_FORMAT='%T Event(s): %e fired for file: %w. Refreshing.'

while inotifywait --exclude '.+\.swp$' -e modify -q \
    -r --timefmt "${TIME_FORMAT}" --format "${OUTPUT_FORMAT}" "$@"; do
    xdotool search --onlyvisible --class chromium windowactivate --sync key F5 \
    search --onlyvisible --class gnome-terminal windowactivate
done

You may need to install inotify and xdotool packages (sudo apt-get install inotify-tools xdotool in Ubuntu) and to change args of --class to the actual names of your preferred browser and terminal.

Start the script as described and just open index.html in a browser. After each save in vim the script will focus your browser's window, refresh it, and then return to the terminal.

2
votes

A quick solution that I sometimes use is to divide the screen into two, and each time a change is made, click on the document xD .

<script>
document.addEventListener("click", function(){
    window.location.reload();
})
</script>
1
votes

In node.js, you can wire-up primus.js (websockets) with gulp.js + gulp-watch (a task runner and change listener, respectively), so that gulp lets your browser window know it should refresh whenever html, js, etc, change. This is OS agnostic and I have it working in a local project.

Here, the page is served by your web server, not loaded as a file from disk, which is actually more like the real thing.

1
votes

The most flexible solution I've found is the chrome LiveReload extension paired with a guard server.

Watch all files in a project, or only the ones you specify. Here is a sample Guardfile config:

guard 'livereload' do
  watch(%r{.*\.(css|js|html|markdown|md|yml)})
end

The downside is that you have to set this up per project and it helps if you're familiar with ruby.

I have also used the Tincr chrome extension - but it appears to be tightly coupled to frameworks and file structures. (I tried wiring up tincr for a jekyll project but it only allowed me to watch a single file for changes, not accounting for includes, partial or layout changes). Tincr however, works great out of the box with projects like rails that have consistent and predefined file structures.

Tincr would be a great solution if it allowed all inclusive match patterns for reloading, but the project is still limited in its feature set.

1
votes

This can be done using a simple python script.

  1. Use pyinotify to monitor a particular folder.
  2. Use Chrome with debugging enabled. Refresh can be done via a websocket connection.

Full details can be referred here.

1
votes

Based on attekei's answer for OSX:

$ brew install fswatch

Chuck all this into reload.scpt:

function run(argv) {
    if (argv.length < 1) {
        console.log("Please supply a (partial) URL to reload");
        return;
    }
    console.log("Trying to reload: " + argv[0]);
    let a = Application("Google Chrome");
    for (let i = 0; i < a.windows.length; i++) {
        let win = a.windows[i];
        for (let j = 0; j < win.tabs.length; j++) {
            let tab = win.tabs[j];
            if (tab.url().startsWith("file://") && tab.url().endsWith(argv[0])) {
                console.log("Reloading URL: " + tab.url());
                tab.reload();
                return;
            }
        }
    }
    console.log("Tab not found.");
}

That will reload the first tab that it finds that starts with file:// and ends with the first command line argument. You can tweak it as desired.

Finally, do something like this.

fswatch -o ~/path/to/watch | xargs -n1 osascript -l JavaScript reload.scpt myindex.html 

fswatch -o outputs the number of files that have changed in each change event, one per line. Usually it will just print 1. xargs reads those 1s in and -n1 means it passes each one as an argument to a new execution of osascript (where it will be ignored).

1
votes

Add this to your HTML

<script> window.addEventListener('focus', ()=>{document.location = document.location})</script>

While you are editing, your browser page is blurred, by switching back to look at it, the focus event is fired and the page reloads.

1
votes

If you are you are using visual studio code (which I highly recommend for Web Development), there is an extension by the name Live Server by Ritwick Dey with more than 9 million downloads. Just install it (recommended to restart vs code after that), and then just right-click on your main HTML file, there will be an option "open with Live Server", click it and your Website will be automatically open in a browser on a local server.

0
votes

Install and set up chromix

Now add this to your .vimrc

autocmd BufWritePost *.html,*.js,*.css :silent ! chromix with http://localhost:4500/ reload

change the port to what you use

0
votes
(function() {
    setTimeout(function(){
        window.location.reload(true);
    }, 100);
})();

Save this code into a file livereload.js and include it at the bottom of the HTML script like so:

<script type="text/javascript" src="livereload.js"></script>

What will this do is refresh the page every 100 mili-seconds. Any changes you make in code are instantly visible to the eyes.

0
votes

Ok, here is my crude Auto Hotkey solution (On Linux, try Auto Key). When the save keyboard shortcut gets pressed, activate the browser, click the reload button, then switch back to the editor. Im just tired of getting other solutions running. Wont work if your editor does autosave.

^s::   ; '^' means ctrl key. '!' is alt, '+' is shift. Can be combined.
    MouseGetPos x,y
    Send ^s

    ; if your IDE is not that fast with saving, increase.
    Sleep 100

    ; Activate the browser. This may differ on your system. Can be found with AHK Window Spy.
    WinActivate ahk_class Chrome_WidgetWin_1
    WinWaitActive ahk_class Chrome_WidgetWin_1
    Sleep 100   ; better safe than sorry.

    ;~ Send ^F5   ; I dont know why this doesnt work ...
    Click 92,62   ; ... so lets click the reload button instead.

    ; Switch back to Editor. Can be found with AHK Window Spy.
    WinActivate ahk_class zc-frame
    WinWaitActive ahk_class zc-frame
    Sleep 100   ; better safe than sorry.

    MouseMove x,y
    return
0
votes

Offline solution using R

This code will:

  • setup a local server using the given .html-file
  • return the server adress, so that you can watch it in a browser.
  • make the browser refresh everytime a change is saved to the .html-file.

    install.packages("servr")
    servr::httw(dir = "c:/users/username/desktop/")
    

Similar solutions exist for python etc.

0
votes

If you have Node installed on your computer, then you can use light-server.

Setp 1: Install light-server using command npm install -g light-server

Step 2: While current working directory is the folder containing the static HTML page, start light-server using command npx light-server -s . -p 5000 -w "*.css # # reloadcss" -w "*.html # # reloadhtml" -w "*.js # # reloadhtml"

Step 3: Open the web page in browser at http://localhost:5000


In Step 2,

Port can be changed using -p switch

Files that are being watched can be changed using -w switch

Server directory can be changed using -s switch

Documentation for light-server is at https://www.npmjs.com/package/light-server

0
votes

Add this in your "head" section. change the time from 3000ms to any value which you prefer. A small hack to reload html file every 3secs. This is useful to me when I use vim + browser setup for JS development.

    <script>
        function autoreload() {
            location.reload();
        }
        setInterval(autoreload, 3000);
    </script>
-1
votes
pip install https://github.com/joh/when-changed/archive/master.zip

alias watch_refresh_chrome=" when-changed -v -r -1 -s ./ osascript -e 'tell application \"Google Chrome\" to tell the active tab of its first window to reload' "

then just enter the directory you want to monitor execute "watch_refresh_chrome"