sindresorhus / open

Open stuff like URLs, files, executables. Cross-platform.
MIT License
3.18k stars 219 forks source link

Re-use same browser tab #256

Open evantahler opened 3 years ago

evantahler commented 3 years ago

open() is awesome - thanks!

It would helpful to be able to re-use the same tab rather than opening a new tab on each invocation.

Here's some prior-art: https://stackoverflow.com/questions/48913566/how-does-create-react-app-re-use-an-existing-browser-tab-after-running-npm-run/48915952

sindresorhus commented 3 years ago

Not something I plan to work on, but a high-quality pull request would be accepted.

The logic should be implemented in JXA, not AppleScript, for readability.

vjpr commented 2 years ago

Just a note that Sindre's https://github.com/sindresorhus/run-jxa might make this easy to implement.

Here is some code I used in a shell script:

# a. Open normally
# open $URL

# b. Open in current tab.
# osascript -e "tell application \"Google Chrome\"
#     if not (exists window 1) then reopen
#     set URL of active tab of window 1 to \"$URL\"
# end tell"

# c. Find existing tab, open and focus.
# From: https://superuser.com/a/1015721/23916
CMD="tell application \"Google Chrome\"
    activate
    repeat with w in (windows)
        set j to 0
        repeat with t in (tabs of w)
            set j to j + 1
            if URL of t contains \"${BASE_URL}\" then
                set (active tab index of w) to j
                set index of w to 1
                tell application \"System Events\" to tell process \"Google Chrome\"
                    perform action \"AXRaise\" of window 1 -- set 'index' doesn't always raise the window
                end tell

                set URL of (active tab of w) to \"$URL\"
                -- set value of text field 1 of toolbar 1 of window 1 to \"$URL\"
                -- keystroke return

                return
            end if
        end repeat
    end repeat
    open location \"${URL}\"
end tell"

osascript -e "${CMD}"
freiserg commented 2 years ago

This package is used in webpack-dev-server. There is a ticket to re-use current tab https://github.com/webpack/webpack-dev-server/issues/1400 It would be easy to implement there this feature

hcw2175 commented 1 year ago

Hey,I fount it work for me with webpack 5 like this:

// you could install react-dev-utils
import openBrowser from "react-dev-utils/openBrowser";

// webpack devServer config
{
  devServer: {
    host: '0.0.0.0',
    port: 8080,
    hot: false,
    onListening: function (devServer) {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined');
      }
      const addr = devServer.server.address();
      openBrowser(`http://${addr.address}:${addr.port}`);
    },
  }
}

good luck