如何使本地HTML页面在文件更改时自动刷新?

hal*_*leo 5 html javascript page-refresh local-files

我通过file://协议在默认浏览器中查看本地HTML文件。

我想在HTML文件中添加一些代码/脚本,以便在文件更改时(最好是在更改CSS文件时)浏览器刷新页面。

我试图通过包括Live.js

<script type="text/javascript" src="http://livejs.com/live.js"></script>
Run Code Online (Sandbox Code Playgroud)

但对于通过访问的文件似乎没有任何作用file://。-有什么可行的解决方案吗?

PS 1:我发现了另一个与此问题有关的问题,但是它不能解决本地文件的问题。

PS 2:我知道我可以通过定期重新加载页面

<meta http-equiv="refresh" content="1">
Run Code Online (Sandbox Code Playgroud)

但这不是我所需要的;我需要重新加载更改。

hac*_*rb9 5

更通用的解决方案

仅靠Javascript似乎无法解决这个问题。在浏览器重新添加以前的支持之前,我认为不存在完美的通用解决方案。

虽然我认为我以前的Emacs解决方案是一个很好的解决方案,但对于使用没有内置 Web 服务器的文本编辑器的人来说,这里有另一个更广泛的答案。

使用inotifywait

许多操作系统可以设置一个程序,以便在文件被修改时执行,而无需轮询。没有适用于所有操作系统的 API,但 Linux 的inotify比大多数操作系统都工作得更好并且易于使用。

这是一个 shell 脚本,当在 HTML 和 CSS 文件所在的目录中运行时,它将告诉 Firefox 在保存更改时重新加载。如果您希望它只观看几个文件,您也可以使用特定的文件名来调用它。

#!/bin/bash
# htmlreload
# When an HTML or CSS file changes, reload any visible browser windows.
# Usage:
# 
#     htmlreload [ --browsername ] [ files ... ]
#
# If no files to watch are specified, all files (recursively) in the
# current working directory are monitored. (Note: this can take a long
# time to initially setup if you have a lot of files).
#
# An argument that begins with a dash is the browser to control.
# `htmlreload --chrom` will match both Chromium and Chrome.

set -o errexit
set -o nounset

browser="firefox"      # Default browser name. (Technically "X11 Class")
keystroke="CTRL+F5"    # The key that tells the browser to reload.

sendkey() {
    # Given an application name and a keystroke,
    # type the key in all windows owned by that application.
    xdotool search --all --onlyvisible --class "$1" \
        key --window %@ "$2"
}

# You may specify the browser name after one or more dashes (e.g., --chromium)
if [[ "${1:-}" == -* ]]; then
    browser="${1##*-}"
    shift
fi

# If no filenames given to watch, watch current working directory.
if [[ $# -eq 0 ]]; then
    echo "Watching all files under `pwd`"
    set - --recursive "`pwd`" #Added quotes for whitespace in path
fi

inotifywait --monitor --event CLOSE_WRITE "$@" | while read; do
    #echo "$REPLY"
    sendkey $browser $keystroke
done
Run Code Online (Sandbox Code Playgroud)

先决条件:inotifywait 和 xdotool

您需要inotifywaitxdotool安装才能使其正常工作。在 Debian GNU/Linux(及其后代,例如 Ubuntu 和 Mint)上,您可以使用单个命令获取这些程序:

sudo apt install inotify-tools xdotool
Run Code Online (Sandbox Code Playgroud)

可选:使用 Chromium

我建议使用 Firefox,因为 Chromium(和 Chrome)在没有焦点的窗口中处理输入的方式很奇怪。如果你绝对必须使用 Chromium,你可以使用这个sendkey()例程:

sudo apt install inotify-tools xdotool
Run Code Online (Sandbox Code Playgroud)

可选:在 Wayland 工作

我还没有测试过它,但读到 Wayland 现在有一个ydotool名为的程序,它是xdotool.


Her*_*tar 2

出于安全原因,浏览器限制对该file:///协议的访问。在 Firefox 中,甚至扩展程序也不再能够访问本地文件,因此您很可能必须在本地提供文件才能使用实时重新加载脚本。如果你这样做,你可以只使用 Live.js,但类似这样的设置可能会稍微简单一些。(需要 Node.js)