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

VimGoogle ChromeAutomation

Vim Problem Overview


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?

Vim Solutions


Solution 1 - Vim

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.

Solution 2 - Vim

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.

Solution 3 - Vim

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

Solution 4 - Vim

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!

Solution 5 - Vim

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

Solution 6 - Vim

Update: Tincr is dead.

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

Solution 7 - Vim

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

Solution 8 - Vim

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

Solution 9 - Vim

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.

Solution 10 - Vim

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.

Solution 11 - Vim

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/

Solution 12 - Vim

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.

Solution 13 - Vim

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>

Solution 14 - Vim

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.

Solution 15 - Vim

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.

Solution 16 - Vim

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.

Solution 17 - Vim

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.

Solution 18 - Vim

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

Solution 19 - Vim

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.

Solution 20 - Vim

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

Solution 21 - Vim

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

Solution 22 - Vim

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

Solution 23 - Vim

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.

Solution 24 - Vim

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

Solution 25 - Vim

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>

Solution 26 - Vim

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;
    }

Solution 27 - Vim

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

Solution 28 - Vim

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

Solution 29 - Vim

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin BurkeView Question on Stackoverflow
Solution 1 - VimleekaiintheskyView Answer on Stackoverflow
Solution 2 - VimalebagranView Answer on Stackoverflow
Solution 3 - VimattekeiView Answer on Stackoverflow
Solution 4 - VimAlvaroView Answer on Stackoverflow
Solution 5 - VimmilkypostmanView Answer on Stackoverflow
Solution 6 - VimKonstantin SpirinView Answer on Stackoverflow
Solution 7 - VimKonstantin SpirinView Answer on Stackoverflow
Solution 8 - VimJibinView Answer on Stackoverflow
Solution 9 - VimS.GoswamiView Answer on Stackoverflow
Solution 10 - VimManpreet Singh DhillonView Answer on Stackoverflow
Solution 11 - VimkemblinView Answer on Stackoverflow
Solution 12 - VimscripterView Answer on Stackoverflow
Solution 13 - VimsRBill1990View Answer on Stackoverflow
Solution 14 - Vimamit.exeView Answer on Stackoverflow
Solution 15 - VimmatansterView Answer on Stackoverflow
Solution 16 - Vimlfender6445View Answer on Stackoverflow
Solution 17 - VimSakthi Priyan HView Answer on Stackoverflow
Solution 18 - VimTimmmmView Answer on Stackoverflow
Solution 19 - VimpinoyyidView Answer on Stackoverflow
Solution 20 - VimmeainView Answer on Stackoverflow
Solution 21 - Vimuser7090116View Answer on Stackoverflow
Solution 22 - VimNils LindemannView Answer on Stackoverflow
Solution 23 - VimRasmus LarsenView Answer on Stackoverflow
Solution 24 - VimDudeView Answer on Stackoverflow
Solution 25 - VimRiteshView Answer on Stackoverflow
Solution 26 - VimSikini JosephView Answer on Stackoverflow
Solution 27 - VimAhmed AliView Answer on Stackoverflow
Solution 28 - Vim Юрий СветловView Answer on Stackoverflow
Solution 29 - VimPegasusView Answer on Stackoverflow