Auto-reload browser when I save changes to html file, in Chrome?
Asked Answered
O

24

167

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?

Ornstead answered 7/4, 2011 at 23:6 Comment(6)
For Firefox: #1347216Seismo
After looking for some time for works everywhere solution I coded my own: alexshulzhenko.ru/web-development-autorefresh-page-on-changesLabialize
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.Ingleside
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?Roulette
@Roulette 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.Ingleside
@Ingleside 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?Roulette
M
152

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.

Madelyn answered 6/4, 2015 at 6:27 Comment(5)
You can put this at the top and also use python -m SimpleHTTPServer easy peasyDeangelo
An alternative PHP version is php -S localhost:8080Sheathing
There is also python3 -m http.server, as well as many more for other languages/tools.Moten
@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.Madelyn
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.Somniferous
R
50

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.

Robinrobina answered 30/6, 2015 at 14:49 Comment(0)
A
40

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!

Adenovirus answered 16/7, 2019 at 19:38 Comment(1)
I use the server of ntl dev and not express. I do not know the local server of netlify, it is not express. Reload does not work with either of the two options a) in an existing express app or b) creating its own express appJesse
P
29

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://mcmap.net/q/92670/-is-there-a-command-like-quot-watch-quot-or-quot-inotifywait-quot-on-the-mac

Polloch answered 21/9, 2016 at 19:31 Comment(2)
Thank you! this is the only answer that works in August 2017! This should be marked as the answer.Rance
Still going strong in November 2023. Thank you! Even works if the file is loaded via the local web server (not direct from the file system). ★★★★★Cotta
P
23

Update: Tincr is dead.

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

Pulvinate answered 6/7, 2013 at 17:20 Comment(8)
This tool is amazing. Among other things, you can refresh the CSS on a page without refreshing the HTML/JS.Concinnate
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 changesInfertile
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).Martineau
No longer available.Washing
I did not found it in the gallery of exts , but found that DevTools AutosaveStudied
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 (#13930745)Studied
Here is Tincr but it only live-releads CSS and Javascript, not HTML.Vigil
The last link by Timmmm is also obsolete.Brief
P
14

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.

Pulvinate answered 2/6, 2016 at 13:40 Comment(2)
Where do you put the gulpfile.js?Washing
In my opinion it's simpler to (on Linux) install nodejs and npm sudo apt install nodejs npm. Then you can do npm -g install browser-sync, and finally browser-sync start --server --files "*.html", "*.css".Scuta
L
8

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.

Lomax answered 22/6, 2021 at 18:42 Comment(2)
I think you need --allow-file-access-from-files for this to work on file://. More details. (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, then it will not be able to detect the change)Marshallmarshallese
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.Lomax
L
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.

Lvov answered 1/10, 2019 at 21:29 Comment(2)
Also, very similar in 2023: The Gnome Web browser, aka epiphany. sudo apt install epiphany-browser, invoke as epiphany <filename>Shingly
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)Shingly
K
6

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.

Kagoshima answered 24/1, 2021 at 12:1 Comment(0)
E
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.

Eisenhart answered 4/12, 2014 at 20:23 Comment(1)
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.Complicate
A
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.

Affection answered 28/4, 2014 at 12:13 Comment(1)
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?Washing
I
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.

Infertile answered 18/9, 2014 at 4:1 Comment(0)
V
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).

Vigil answered 17/8, 2017 at 10:2 Comment(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://.Trevethick
T
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>
Thesaurus answered 21/3, 2019 at 6:40 Comment(1)
I think having to grab the mouse and make a click is part of what the OP (and me) is trying to avoid having to have to do.Shingly
S
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.

Spatial answered 2/8, 2020 at 20:55 Comment(1)
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.Shingly
P
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

Presentment answered 21/5, 2016 at 7:23 Comment(0)
L
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
Lotion answered 22/3, 2019 at 12:37 Comment(0)
E
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.

Eventide answered 16/2, 2020 at 19:16 Comment(0)
M
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

Medico answered 18/11, 2020 at 8:33 Comment(0)
D
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;
    }
Dincolo answered 15/2, 2022 at 10:23 Comment(0)
C
0

Here's something I found works for MacOS:

fswatch -o . | xargs -n1 -I {} osascript -l JavaScript -e "Application(\"chrome\").windows[0].tabs.whose({url: {_contains: '$(pwd)'}})[0].reload()"

fswatch will watch the current directory and when a file in that dir changes, it will call a MacOS automation script (osascript) to refresh the proper chrome tab (tabs.whose({url: {_contains: '$(pwd)'}})[0])

Clifton answered 8/1 at 4:36 Comment(0)
K
-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"

Kaseykasha answered 21/9, 2017 at 2:25 Comment(0)
M
-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.

Mending answered 25/11, 2018 at 7:51 Comment(2)
This does not answer the question.Roll
Yeah correct, but I still think it's useful in situations where user wants constant refresh of his HTML document. I respect your honesty sir.Mending
E
-1

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>
Ethiopia answered 20/5, 2021 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.