From 1764b55dbdfd922755d6204b042e367cb9221737 Mon Sep 17 00:00:00 2001 From: Jonas Tranberg Date: Sun, 5 Jul 2020 03:10:08 +0200 Subject: [PATCH] Added failed load detection --- README.md | 1 + internal/browser/browser.go | 17 +++++++++++++++++ internal/browser/tab.go | 18 +++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c3481c..82d15df 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ YAML configurable web dashboard viewer written in Go - Cron jobs - System commands - Message flashing +- Detect failed page loads and retry ## About diff --git a/internal/browser/browser.go b/internal/browser/browser.go index b2abb46..4c972ab 100644 --- a/internal/browser/browser.go +++ b/internal/browser/browser.go @@ -4,7 +4,10 @@ import ( "context" "log" + "github.com/chromedp/cdproto/network" + "github.com/chromedp/cdproto/target" "github.com/chromedp/chromedp" + "github.com/sirupsen/logrus" ) type Browser struct { @@ -39,6 +42,20 @@ func (b *Browser) NewTab() Tab { Context: ctx, } + chromedp.ListenTarget(ctx, func(ev interface{}) { + if e, ok := ev.(*network.EventLoadingFailed); ok { + if e.Type == network.ResourceTypeDocument { + logrus.Infof("Tab failed to load, reloading in %v seconds\n", FailedLoadReloadDelay.Seconds()) + + go t.delayedReload() + } + } + + if _, ok := ev.(*target.EventTargetDestroyed); ok { + b.removeTab(t) + } + }) + t.Close = func() { b.removeTab(t) close() diff --git a/internal/browser/tab.go b/internal/browser/tab.go index b1831a3..5945d50 100644 --- a/internal/browser/tab.go +++ b/internal/browser/tab.go @@ -3,6 +3,7 @@ package browser import ( "context" "encoding/base64" + "time" "github.com/chromedp/cdproto/network" "github.com/chromedp/cdproto/page" @@ -10,11 +11,17 @@ import ( "github.com/chromedp/chromedp" ) +var ( + FailedLoadReloadDelay = time.Second * 10 +) + type Tab struct { Browser Browser Context context.Context Close func() + + isReloading bool } type BasicAuthCredentials struct { @@ -31,7 +38,7 @@ func (t *Tab) Reload() { } func (t *Tab) Navigate(url string) { - chromedp.Run(t.Context, chromedp.Navigate(url)) + chromedp.Run(t.Context, network.Enable(), chromedp.Navigate(url)) } func (t *Tab) NavigateWithBasicAuth(url string, creds BasicAuthCredentials) { @@ -69,3 +76,12 @@ func (t *Tab) AddJS(script string) { chromedp.EvaluateAsDevTools(script, &executed), ) } + +func (t *Tab) delayedReload() { + if !t.isReloading { + t.isReloading = true + time.Sleep(FailedLoadReloadDelay) + t.isReloading = false + t.Reload() + } +}