更通用的解决方案
单靠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
先决条件:inotifywait 和 xdotool
您需要安装 inotifywait 和 xdotool 才能正常工作。在 Debian GNU/Linux(以及后代,如 Ubuntu 和 Mint)上,您可以使用单个命令获取这些程序:
sudo apt install inotify-tools xdotool
可选:使用 Chromium
我建议使用 Firefox,因为 Chromium(和 Chrome)处理没有焦点的窗口中的输入的方式很奇怪。如果您绝对必须使用 Chromium,则可以改用此 sendkey() 例程:
sendkeywithfocus() {
# Given an application name and a keystroke, give each window
# focus and type the key in all windows owned by that application.
# This is apparently needed by chromium, but is annoying because
# whatever you're typing in your text editor shortly after saving
# will also go to the chromium window.
# Save previous window id so we can restore focus.
local current_focus="$(xdotool getwindowfocus)"
# For each visible window, focus it and send the keystroke.
xdotool search --all --onlyvisible --class "$1" \
windowfocus \
key --window %@ "$2"
# Restore previous focus.
xdotool windowfocus "$current_focus"
}
可选:在 Wayland 工作
我尚未对其进行测试,但得知 Wayland 现在有一个名为 ydotool 的程序,它是 xdotool 的替代品。