openChrome.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright (c) 2015-present, Facebook, Inc.
  3. This source code is licensed under the MIT license found in the
  4. LICENSE file at
  5. https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  6. */
  7. /* global Application */
  8. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  9. function run(argv) {
  10. const urlToOpen = argv[0]
  11. // Allow requested program to be optional, default to Google Chrome
  12. const programName = argv[1] ?? 'Google Chrome'
  13. const app = Application(programName)
  14. if (app.windows.length === 0) {
  15. app.Window().make()
  16. }
  17. // 1: Looking for tab running debugger then,
  18. // Reload debugging tab if found, then return
  19. const found = lookupTabWithUrl(urlToOpen, app)
  20. if (found) {
  21. found.targetWindow.activeTabIndex = found.targetTabIndex
  22. found.targetTab.reload()
  23. found.targetWindow.index = 1
  24. app.activate()
  25. return
  26. }
  27. // 2: Looking for Empty tab
  28. // In case debugging tab was not found
  29. // We try to find an empty tab instead
  30. const emptyTabFound = lookupTabWithUrl('chrome://newtab/', app)
  31. if (emptyTabFound) {
  32. emptyTabFound.targetWindow.activeTabIndex = emptyTabFound.targetTabIndex
  33. emptyTabFound.targetTab.url = urlToOpen
  34. app.activate()
  35. return
  36. }
  37. // 3: Create new tab
  38. // both debugging and empty tab were not found make a new tab with url
  39. const firstWindow = app.windows[0]
  40. firstWindow.tabs.push(app.Tab({ url: urlToOpen }))
  41. app.activate()
  42. }
  43. /**
  44. * Lookup tab with given url
  45. */
  46. function lookupTabWithUrl(lookupUrl, app) {
  47. const windows = app.windows()
  48. for (const window of windows) {
  49. for (const [tabIndex, tab] of window.tabs().entries()) {
  50. if (tab.url().includes(lookupUrl)) {
  51. return {
  52. targetTab: tab,
  53. targetTabIndex: tabIndex + 1,
  54. targetWindow: window,
  55. }
  56. }
  57. }
  58. }
  59. }