Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto-reload html file with a browser via terminal command

I am trying to do some small html web stuff, and would find it incredibly useful to be able to see live updates of the html file viewed through a browser whenever I save my file. I know there are probably IDEs out there that do this for you, and if you recommend any, please do, but I am looking to make a script that will just open the file in the browser, while closing the version of the file that was already open, so that I can continue to do all my programming in vim.

I know that I can use the following in Mac OSX, to open the file into a new tab of my current browser:

open foo.html

but, if I have this occurring on a timed loop, or every time I write (:w) in vim, my browser will fill up with new tabs. Is there a way to close the old tab when opening the new tab? Or is there an even better approach to this that I have not considered? It would be highly preferred if I could continue to use vim in terminal.

Thanks in advance.

like image 463
StrugglingProgrammer Avatar asked Jun 15 '13 00:06

StrugglingProgrammer


2 Answers

You can use AppleScript to reload the tab. See the Benjie's answer for this question
Use osascript to call the AppleScript from shell script. You'll get something like this:

osascript -e 'tell application "Google Chrome" to tell the active tab of its first window to reload'

Alternatively you can use something like next to close all previous tabs:

tell application "Google Chrome"
    set windowList to every tab of every window whose URL starts with "http://stackoverflow.com"
    repeat with tabList in windowList
        repeat with thisTab in tabList
            close thisTab
        end repeat
    end repeat
end tell
like image 135
cody Avatar answered Oct 10 '22 16:10

cody


If there is already a tab for foo.html, open foo.html should focus that tab in Safari. For Chrome, you might use something like this:

set u to "http://t.co/"
tell application "Google Chrome"
    repeat with w in windows
        set i to 0
        repeat with t in tabs of w
            set i to i + 1
            if URL of t is u then
                set active tab index of w to i
                set index of w to 1
                tell t to reload
                activate
                return
            end if
        end repeat
    end repeat
    open location u
    activate
end tell

I have just assigned ⌘R to open "$TM_FILEPATH" -a Safari in the text.html scope in TextMate. I have also enabled saving documents when switching to another application, so it basically does the last three steps of the edit-save-switch application-refresh cycle.

Other options:

  • http://livereload.com
  • http://brettterpstra.com/2011/03/07/watch-for-file-changes-and-refresh-your-browser-automatically
like image 31
Lri Avatar answered Oct 10 '22 16:10

Lri