How can I programmatically get the Terminal scrollback text?

Assuming there is only one instance of the file:///.../index.html URL in the contents of the entire scrolling buffer of the tab, then the following example AppleScript code can do that:

tell application "Terminal" to ¬
    set tabHistory to ¬
        history of tab of ¬
        front window as text

set fileURL to ¬
    do shell script ¬
        "grep -o 'file:///.*\\.html' <<< " & ¬
        tabHistory's quoted form & "; exit 0"

if fileURL is not "" then ¬
    do shell script ¬
        "open " & fileURL's quoted form

Notes:

The example AppleScript code above acts on the selected tab of the front window in Terminal.

If there is a file:///.../index.html URL in the contents of the entire scrolling buffer it will be opened by the open command.

If there is more than one instance of the file:///.../index.html URL in the contents of the entire scrolling buffer of the tab, then make the following change in the example AppleScript code above to open the last instance of the file:///.../index.html URL:

Change:

set fileURL to ¬
    do shell script ¬
        "grep -o 'file:///.*\\.html' <<< " & ¬
        tabHistory's quoted form & "; exit 0"

To:

set fileURL to ¬
    last paragraph of ¬
    (do shell script ¬
        "grep -o 'file:///.*\\.html' <<< " & ¬
        tabHistory's quoted form & "; exit 0")

If you want to use Safari to open the URL and have it frontmost, then:

Change:

if fileURL is not "" then ¬
    do shell script ¬
        "open " & fileURL's quoted form

To:

if fileURL is not "" then ¬
    tell application "Safari"
        make new document with properties {URL:fileURL}
        activate
    end tell

The example AppleScript code can be saved as a shell script with a #!/usr/bin/osascript shebang, made executable and run from Terminal.


Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.