Repository navigation
Expand file tree
/
Copy pathCloseBrowser.go
More file actions
78 lines (71 loc) · 2.4 KB
/
Copy pathCloseBrowser.go
File metadata and controls
78 lines (71 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package devbrowser
import (
"context"
"time"
"webtyp.com/devbrowser/chromedp"
)
const gracefulCloseTimeout = 3 * time.Second
// shutdownChrome asks Chrome to close itself first (Browser.close): a process
// killed by the allocator records exit_type "Crashed" in the profile, and the
// next start shows the "Restore pages?" bubble over DevTools. The allocator
// cancel below still runs, so a hung Chrome is killed and no second window
// survives (the about:blank "double window" bug).
func (h *DevBrowser) shutdownChrome() {
// Only a context that actually started Chrome can close it gracefully.
// Without a browser, chromedp's "allocated" channel is a one-token
// semaphore: chromedp.Cancel would take the token and h.Cancel below would
// then wait for a second one forever.
closeRoot := h.rootCtx
if closeRoot == nil {
closeRoot = h.Ctx
}
if closeRoot != nil {
if c := chromedp.FromContext(closeRoot); c != nil && c.Browser != nil {
closeCtx, closeCancel := context.WithTimeout(closeRoot, gracefulCloseTimeout)
_ = chromedp.Cancel(closeCtx)
closeCancel()
}
h.rootCtx = nil
h.Ctx = nil
}
// The allocator goes BEFORE the context cancel. When the graceful close
// fails, chromedp has already marked the browser as closing itself and
// returns without killing it; the context cancel then waits for the
// process to exit, forever. Cancelling the allocator kills a Chrome that is
// still alive (a no-op when it already exited), so the wait below ends.
if h.AllocCancel != nil {
h.AllocCancel()
h.AllocCancel = nil
}
if h.Cancel != nil {
h.Cancel()
h.Cancel = nil
}
// Each extra tab derives from Ctx, so the cancel above already closed it.
for _, t := range h.extraTabs {
t.cancel()
}
h.extraTabs = nil
h.mainTab = nil
h.active.Store(nil)
}
// CloseBrowser reports AFTER releasing h.Mu: the logger and the UI of every TUI call back into the browser
// (GetLastOperationID, IsOpen), and reporting under the lock deadlocked the daemon's Shutdown for good.
func (h *DevBrowser) CloseBrowser() error {
h.Mu.Lock()
wasOpen := h.IsOpenFlag
h.IsOpenFlag = false
h.ready = false
h.pendingReload = false
// The next browser context needs its listeners again; the history is cleared
// by the first navigation of the new context.
h.lastPanelNodeID = 0
h.shutdownChrome()
status := h.StatusMessage()
h.Mu.Unlock()
if wasOpen {
h.Logger(status)
h.UI.RefreshUI()
}
return nil
}