Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 959
Kevin Burke Avatar asked Apr 07 '11 23:04

Kevin Burke


People also ask

How do I make HTML refresh automatically?

Approach 1: One can auto refresh the webpage using the meta tag within the head element of your HTML using the http-equiv property. It is an inbuilt property with HTML 5. One can further add the time period of the refresh using the content attribute within the Meta tag.

How do I automatically refresh Chrome browser?

To configure it, click on the puzzle piece icon in the top-right, then click on the Easy Auto Refresh. Click on the puzzle piece icon, then on “Easy Auto Refresh”. In the popup window, enter the number of seconds after which you want the page to refresh, then click “Start”.

How do I make my browser refresh automatically?

It's as simple as going to your browser's app/extension store and finding one you like: Launch your browser. Go to app/extension store (Chrome Web Store, Firefox Add-Ons, Microsoft Edge Add-ons Store, etc.). Enter “auto-refresh” in the search bar.

How do I stop HTML from auto refreshing?

Click the Start button, type “internet options” and select Internet Options in the search results. In the Internet Properties window, click “Custom tab -> Custom level,” then in the Security Settings window, scroll down until you find “Allow META REFRESH.” Disable this option and click OK.


18 Answers

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.

like image 153
leekaiinthesky Avatar answered Oct 14 '22 07:10

leekaiinthesky


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.

like image 33
alebagran Avatar answered Oct 14 '22 05:10

alebagran


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

like image 20
attekei Avatar answered Oct 14 '22 06:10

attekei


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!

like image 24
Alvaro Avatar answered Oct 14 '22 06:10

Alvaro


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

like image 31
milkypostman Avatar answered Oct 14 '22 07:10

milkypostman


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.

like image 39
Konstantin Spirin Avatar answered Oct 14 '22 05:10

Konstantin Spirin


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

like image 22
Jibin Avatar answered Oct 14 '22 05:10

Jibin


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.

like image 32
S.Goswami Avatar answered Oct 14 '22 07:10

S.Goswami


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.

like image 29
Manpreet Singh Dhillon Avatar answered Oct 14 '22 07:10

Manpreet Singh Dhillon


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/

like image 40
kemblin Avatar answered Oct 14 '22 07:10

kemblin


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>
like image 45
hwpoison Avatar answered Oct 14 '22 05:10

hwpoison


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.

like image 29
scripter Avatar answered Oct 14 '22 06:10

scripter


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.

like image 43
pinoyyid Avatar answered Oct 14 '22 06:10

pinoyyid


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.

like image 45
amit.exe Avatar answered Oct 14 '22 06:10

amit.exe


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.

like image 26
matanster Avatar answered Oct 14 '22 06:10

matanster


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.

like image 25
lfender6445 Avatar answered Oct 14 '22 07:10

lfender6445


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.

like image 28
Sakthi Priyan H Avatar answered Oct 14 '22 06:10

Sakthi Priyan H


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

like image 42
Timmmm Avatar answered Oct 14 '22 05:10

Timmmm