157

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Kevin Burke
  • 61,194
  • 76
  • 188
  • 305
  • 3
    For Firefox: http://stackoverflow.com/questions/1346716/how-do-i-make-firefox-auto-refresh-on-file-change – Ciro Santilli OurBigBook.com Dec 11 '14 at 17:07
  • After looking for some time for works everywhere solution I coded my own: http://alexshulzhenko.ru/web-development-autorefresh-page-on-changes/ – Tebe Apr 06 '15 at 21:59
  • I also code my own: Live Reload for Chrome and Firefox: https://github.com/blaise-io/live-reload#readme. Repeat the host URL in the source file URL field of the addon to monitor itself. – Blaise Jul 08 '18 at 19:24
  • 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 Aug 11 '20 at 14:41
  • @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 Aug 12 '20 at 07:54
  • @Blaise It's on localhost, for a very small project. I don't see why the server would have to generate a response every 0.1s, because I don't save nearly that often. It's only about the delay. I know for a fact VS.NET is capable of refreshing fairly quickly, with larger projects even. I'm against the 0.5s limitation in the ux. If you're concerned with other developers' monitoring resources, why not just display a warning message for every setting below 0.5s? – Jay Aug 14 '20 at 16:31

30 Answers30

143

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.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
leekaiinthesky
  • 5,413
  • 4
  • 28
  • 39
  • 7
    You can put this at the top and also use python -m SimpleHTTPServer easy peasy – Marcel Valdez Orozco Dec 14 '16 at 01:06
  • 4
    An alternative PHP version is `php -S localhost:8080` – roryok Jan 26 '17 at 11:38
  • 7
    There is also `python3 -m http.server`, as well as [many more for other languages/tools](https://gist.github.com/willurd/5720255). – carlwgeorge Oct 28 '17 at 22:23
  • 3
    @arvixx It does work with local files, as long as you are running a local http server (and use http(s)://). I agree it doesn't work with the file:// uri scheme though, if that's what you mean. See Marcel Valdez Orozco's comment above for one easy way to instantaneously create an http server from your local directory. – leekaiinthesky Sep 30 '19 at 18:24
  • 2
    Not a scalable solution, I'm afraid. If you have hundreds of asset files, then you will have a massive CPU from the HEAD requests. Also clutters up your network tab. – Zephyr was a Friend of Mine Aug 13 '22 at 11:30
46

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.

alebagran
  • 675
  • 5
  • 5
  • 2
    this also works with local files. For me, this is the correct answer. – pid Jul 24 '20 at 12:19
  • 4
    This works well for rapid prototyping; however since the refresh is scheduled (rather than responding to an on-save event) ability to use Chrome DevTools is limited. – Mikhail Golubitsky Jan 03 '21 at 20:50
  • Only useful for static HTML, with no JS . Every refresh will refresh the state of your JS app. – Chris Dec 03 '22 at 16:21
35

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!

Alvaro
  • 1,853
  • 18
  • 24
27

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

user202729
  • 3,358
  • 3
  • 25
  • 36
attekei
  • 491
  • 4
  • 10
23

Update: Tincr is dead.

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

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187
Konstantin Spirin
  • 20,609
  • 15
  • 72
  • 90
  • 4
    This tool is amazing. Among other things, you can refresh the CSS on a page without refreshing the HTML/JS. – Mud Jan 14 '14 at 18:11
  • looks promising but I tried wiring up tincr for a jekyll project - it only allowed me to watch a single file for changes, not accounting for includes, partial or layout changes – random-forest-cat Mar 12 '15 at 14:55
  • 3
    Unfortunately, Tincr uses NPAPI which is deprecated and is disabled in Chrome by default (since Apr 2015). And it will be entirely removed soon (Sep 2015). – Jan Včelák Apr 21 '15 at 23:38
  • 4
    No longer available. – nu everest Aug 03 '16 at 18:10
  • 2
    I did not found it in the gallery of exts , but found that DevTools Autosave – mercury Sep 19 '16 at 01:42
  • I think I may have an explanation. Having a look at the google groups for Tincr, it appears Tincr does not support html file refresh, and that it can only detect changes in either css or javascript. Copied from here (http://stackoverflow.com/questions/13930245/how-to-use-the-tincr-google-chrome-extension-for-live-reloading-local-files) – mercury Mar 18 '17 at 01:56
  • [Here is Tincr](https://chrome.google.com/webstore/detail/tincr/lfjbhpnjiajjgnjganiaggebdhhpnbih) but it only live-releads CSS and Javascript, not HTML. – Timmmm Aug 17 '17 at 09:01
  • 1
    The last link by Timmmm is also obsolete. – isherwood Feb 16 '20 at 16:04
23

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-page-mo/hgeljhfekpckiiplhkigfehkdpldcggm?hl=en

Community
  • 1
  • 1
milkypostman
  • 2,955
  • 27
  • 23
  • 28
    That plugin doesn't seem to watch the local filesystem, and will instead just refresh periodically. – Dan Dascalescu Aug 15 '12 at 07:55
  • I was getting errors when changing the browser to chrome. To fix it, change the `keyword` to `watch_keyword` in the following line: `if (URL of atab contains "#{keyword}") then` – Tim Joyce Dec 13 '12 at 11:38
  • Whau! I'm using the script from your first link (http://goo.gl/FZJvdJ) with some little mods for Dart-Development with Chromium. Works like a charm! – Mike Mitterer Feb 19 '14 at 09:00
  • 2
    It is a pretty old question, but [browser-sync](https://www.browsersync.io) is the tool for exactly that. – miha Feb 22 '16 at 07:59
12

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.

user202729
  • 3,358
  • 3
  • 25
  • 36
Konstantin Spirin
  • 20,609
  • 15
  • 72
  • 90
10

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

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Jibin
  • 117
  • 1
  • 2
7

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.

15 Volts
  • 1,946
  • 15
  • 37
  • Also, very similar in 2023: The Gnome Web browser, aka epiphany. `sudo apt install epiphany-browser`, invoke as `epiphany ` – Jonathan Hartley Jan 16 '23 at 22:00
  • Actually, both of these options are suboptimal for my scenario because they use tabs, and restore old tabs between invocations. I want a plain single-window, no tabs, html viewer that runs as a synchronous process (so the script that invoked it doesn't continue until it the html viewer exits) – Jonathan Hartley Jan 17 '23 at 17:05
6

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.

user202729
  • 3,358
  • 3
  • 25
  • 36
  • I think you need `--allow-file-access-from-files` for this to work on `file://`. [More details](https://stackoverflow.com/questions/48858760/how-do-i-make-a-local-html-page-auto-refresh-on-file-change#comment127632236_48858760). (also there's a little problem, if the file content changes between a refresh and the first fetch (which [takes at least 1s in this implementation](https://stackoverflow.com/questions/6685396/execute-the-setinterval-function-without-delay-the-first-time?noredirect=1), then it will not be able to detect the change) – user202729 May 14 '22 at 13:41
  • I wrote it while working with localhost. It is not for high demanding development environment. If you just want to avoid large scripts, third party tools or browser extensions for a small work, this may help to some extent. – Manpreet Singh Dhillon May 16 '22 at 15:46
5

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.

amit.exe
  • 81
  • 1
  • 2
3

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/

kemblin
  • 31
  • 2
2

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.

scripter
  • 31
  • 2
  • Didn't work (I'm trying to auto-refresh chrome), specifically the xdotool part searching for window class chromium, but I was able to get this to work (the xdotool part that is): `xdotool search --name 127.0.0.1 windowactivate key F5` for working on localhost (127.0.0.1) only, of course. Now I have to plug that back into the script. – Rolf Apr 27 '15 at 21:35
1

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.

matanster
  • 15,072
  • 19
  • 88
  • 167
  • Could you provide a link to a page that shows how to do this or better yet a set of commands to run for those of us not as familiar with node? – nu everest Aug 03 '16 at 18:12
1

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.

random-forest-cat
  • 33,652
  • 11
  • 120
  • 99
1

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

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).

Timmmm
  • 88,195
  • 71
  • 364
  • 509
  • 1
    This is what I was looking for, thanks! Using `tab.title.includes(argv[0])` as the conditional I can match on page title which can be less finicky than URL, and works when using a local server rather than file://. – David Mirabito Jul 02 '20 at 23:34
1

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>
hwpoison
  • 27
  • 2
1

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.

pinoyyid
  • 21,499
  • 14
  • 64
  • 115
  • Having to both save from your editor and then click something else to switch focus (twice!) is, I think, a part of the problem the OP (and I) wishes to see fixed. – Jonathan Hartley Jan 16 '23 at 22:03
0

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

meain
  • 833
  • 9
  • 28
0

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
Nils Lindemann
  • 1,146
  • 1
  • 16
  • 26
0

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.

Rasmus Larsen
  • 5,721
  • 8
  • 47
  • 79
0

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

Dude
  • 199
  • 2
  • 6
0

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>
Ritesh
  • 1
0

Live reload works fine on js and css changes. However it was not working for laravel's blade templates. So I wrote a small script that checks for page changes and reloads if there is change. Am not sure if it is the best way, but it works. I used the script together with Live.js.

Here it is.

    window.addEventListener("load", function(){
        var current_url = window.location.href;
        var current_data = httpGet(current_url);
        var compone = current_data.length;
        setInterval(function(){
        var current_data_twos = httpGet(current_url);
        var componecurrent_data_twos = current_data_twos.length;
        if(compone !=componecurrent_data_twos ){
          location.reload();
        }
      }, 1000);
    });
    function httpGet(theUrl)
    {
        let xmlhttp;

        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                return xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", theUrl, false);
        xmlhttp.send();
        return xmlhttp.response;
    }
0

Just use the Live server extension and open the file with live server. extension namelive server

0

If you're just updating an individual HTML file, Visual Studio Code (vscode) HTML Preview will automatically refresh on update -- it's quite seamless.

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
-1
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"

Pegasus
  • 1,398
  • 15
  • 20
-1
(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.

-1

Live Reload Browser Page

enter image description here

Live Reload Browser Page - tool 2022, for auto refreshing the browser page in real time for Google Chrome.

Additional features

  • auto refreshing the browser page in real time

  • auto HTML validation of the browser page

  • real-time alert on the browser page during web development