Charles Roper
Charles Roper

Reputation: 20625

How do I make Firefox auto-refresh on file change?

Does anyone know of an extension for Firefox, or a script or some other mechanism, that can monitor one or more local files. Firefox would auto-refresh or otherwise update its canvas when it detected a change (of timestamp) in the files(s).

For editing CSS, it would be ideal if just the CSS could be reloaded, rather than a full HTML re-render.

Effectively it would enable similar behaviour to Firebug with its dynamic HTML/CSS editing, only through external files.

Upvotes: 90

Views: 64221

Answers (13)

Richard Neill
Richard Neill

Reputation: 1

The refresher script is really good! But note:

  • you have to exclude whatever file your editor of choice backs up to, unless you want an F5 on every keystroke. For me, (with kwrite) this means also adding 'kate-swp' to the excluded list.

  • the script, as written, re-triggers itself when either Firefox (or Apache) loads the saved file! So add "-e close_write" to the inotifywait options.

  • we're actually setting up and tearing down the inotifywait instance on every ctrl-S. There is probably a cleverer way with the --monitor option.

  • this sends F5 to a firefox window, not a tab.

Upvotes: 0

eternal_frame
eternal_frame

Reputation: 131

Here's a short bash script that does exactly what's asked for: Run without arguments and it will show a cursor to select whatever browser you're using. Otherwise search for the first best window title ("Mozilla Firefox", "Chromium", "Chrome", ...):

./refresher "Chromium" --quiet

It uses inotify-tools to watch for file changes (e.g. .css) and xdotool to refresh the browser. Save the following as refresher and made executable with chmod ugo+x refresher:

# refresher - send F5 to a selected window on file change events
#!/bin/bash

# run in current directory and exclude common patterns:
project_root=$(pwd)
excluded=".*\.(swp|log|.*~)"

# use the first argument to search for a window name or let user select:
if [ -z "$1" ]
then
  echo waiting for the user to select browser window...
  wid=$(xdotool selectwindow)
else
  echo searching for window with name "$1"...
  wid=$(xdotool search --name "$1" | tail -n1)
fi
if [ -z $wid ]
then
  echo window ID not found!
  exit 1
fi
echo using window id [$wid] for xdotool

if [  $# -gt 0 ]
then
  shift
  echo passing remaining $# arguments to inotifywait
fi
while inotifywait $@ --recursive --exclude "$excluded" $project_root
do
  xdotool key --window $wid F5
done

Upvotes: 1

sigsegv
sigsegv

Reputation: 201

This is certainly hacky, but if you want to work locally without making any external request (to live.js, for example), or run any local server, I think this might be useful. This is not specific to web development, you can adopt similar strategy to any other workflow.

You will need two tiny tools (which are present in almost all distribution repos): inotify-tools and xdotool.

First get the ID of your Firefox and your editor window using xdotool.

$ xdotool search --name "Mozilla Firefox"
60817411
60817836
$ xdotool search --name "Pluma"  # Pluma is my editor
94371842

Depending on the number of processes running, you will get one or more window ID. Use xdotool windowactivate <ID> to know which one you want (the focus changes to the respective window).

Use inotifywait -e close_write to monitor changes to your local file and when you save the file using your editor, change focus to your browser, reload xdotool key CTRL+R and focus back to your editor. This is so instantaneous you will not notice nothing.

Also, inotifywait exits on change, so you might have to do it in a loop. Here is a minimum working example (in Bash in your working directory).

while /usr/bin/true
do
    inotifywait -e close_write index.html;
    xdotool windowactivate 60917411;  # Switch to Firefox
    xdotool key CTRL+R;               # Reload Firefox
    xdotool windowactivate 94371842   # Switch back to Pluma
done
  • You can use inotifywait to watch for the entire directory or some selected files in your directory.
  • You can write a script that can automate is easily.
  • This works on Linux (I've tested this on Void Linux.)

Upvotes: 3

weirane
weirane

Reputation: 21

You can use live.js with a tampermonkey script to avoid having to include https://livejs.com/live.js in your HTML file.

// ==UserScript==
// @name         Auto reload
// @author       weirane
// @version      0.1
// @match        http://127.0.0.1/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    if (Number(window.location.port) === 8000) {
        const script = document.createElement('script');
        script.src = 'https://livejs.com/live.js';
        document.body.appendChild(script);
    }
})();

With this tampermonkey script, the live.js script will be automatically inserted to pages whose address matches http://127.0.0.1:8000/*. You can change the port according to your need.

Upvotes: 2

nicorac
nicorac

Reputation: 190

Have a look at FileWatcher extension: https://addons.mozilla.org/en-US/firefox/addon/filewatcher/

  • it's a WebExtension, so it works with the latest Firefox
  • it has a native app (to be installed locally) that monitors watched files for changes using native OS calls (no polling!) and notifies the WebExtension to let it reload the web page
  • reload is driven by rules: a rule contains the page URL (with regular expression support) and its included/excluded local source files
  • open source: https://github.com/coolsoft-ita/filewatcher

DISCLAIMER: I'm the author of the extension ;)

Upvotes: 16

Att Righ
Att Righ

Reputation: 1779

Browsersync can do this from the server side / outside of the browser.

This can achieve more repeatable results / things that don't require so much clicking.

This will serve a page and refresh on change

cd static_content
browser-sync start --server --files .

It also allows a scripting mode.

Upvotes: 4

Aamir Shahzad
Aamir Shahzad

Reputation: 6834

I would recommend livejs

But it has following Advantages and Disadvantages

Advantages:
1. Easy setup
2. Works seamlessly on different browsers (Live.js works in Firefox, Chrome, Safari, Opera and IE6+)
3. Don't add irritating interval for refreshing browser specially when you want to debug along with designing
4. Only refreshing when you save change ctrl + S
5. Directly saves CSS etc from firebug I have not used that feature but read on their site http://livejs.com/ that they support it too!!!

Disadvantages:
1. It will not work on file protocol file:///C:/Users/Admin/Desktop/livejs/live.html
2. You need to have server to run it like http://localhost
3. You have to remove it while deploying on staging/production
4. Doesn't serves CDN I have tried cheating & applying direct link http://livejs.com/live.js but it will not work you have to download and keep on local to work.

Upvotes: 9

Charles Roper
Charles Roper

Reputation: 20625

Live.js

From the website:

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.

It has the huge benefit of working with IETester, dynamically refreshing each open IE tab.

Try it out by adding the following to your <head>

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

Upvotes: 98

bob
bob

Reputation: 933

Firefox has an extension called mozRepl.

Emacs can plug into this, with moz-reload-on-save-mode.

when it's set up, saving the file forces a refresh of the browser window.

Upvotes: 6

Alysko
Alysko

Reputation: 347

Xrefresh with firebug.

Upvotes: 6

Sampson
Sampson

Reputation: 268344

You could just place a javascript interval on your page, have it query a local script which checks the last date modified of the css file, and refreshes it if it changed.

jQuery Example:

var modTime = 0;
setInterval(function(){
  $.post("isModified.php", {"file":"main.css", "time":modTime}, function(rst) {
    if (rst.time != modTime) {
      modTime = rst.time;
      // reload style tag
      $("head link[rel='stylesheet']:eq(0)").remove();
      $("head").prepend($(document.createElement("link")).attr({
          "rel":"stylesheet",
          "href":"http://sstatic.net/mso/all.css?v=4372"
        })
      );
    }
  });
}, 5000);

Upvotes: 4

mck89
mck89

Reputation: 19241

I think that you can solve it by using some ajax requests after a determinate interval. You can do a request to CSS files and then if you don't get the "not modified" header you delete your css and load it again. For dynamic files you do a request and store the response and then every time you make a request to that file you compare the response to the latest.

Upvotes: 0

Mike Buckbee
Mike Buckbee

Reputation: 6983

There are some IDE's that contain this ability (They'll have a pane within them or some other means to auto-refresh a page on save).

If you want to do this yourself a quick hack is to set the meta refresh on the page to a low value - one or two seconds.

# Will refresh the page content every second
<meta http-equiv="refresh" content="1" />

Upvotes: 5

Related Questions