Skip to content

Commit 397b489

Browse files
author
=
committed
Fix json protocol
Updates gcdapi and json protocol to use PUT
1 parent 7739c78 commit 397b489

33 files changed

+914
-198
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# Changelog (2023)
2+
- 2.3.0 (Mar 28) Updated JSON endpoint calls to use PUT instead of GET as GET returns an error since 111.
3+
- Updates to chrome 111.0.5563.147 protocol
4+
15
# Changelog (2022)
26
- 2.2.6 (Sept 5th) Fixes a bug where new types that were just arrays to another ref type were not being output correctly
37
- Updates to chrome 105.0.5195.102

gcd.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,7 @@ func (c *Gcd) getConnectableTargets() ([]*TargetInfo, error) {
291291
targets := make([]*TargetInfo, 0)
292292
err = json.Unmarshal(body, &targets)
293293
if err != nil {
294+
fmt.Printf("%s\n", string(body))
294295
return nil, &GcdDecodingErr{Message: err.Error()}
295296
}
296297

gcd_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ var (
2727
func init() {
2828
switch runtime.GOOS {
2929
case "windows":
30-
flag.StringVar(&testPath, "chrome", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "path to chrome")
30+
flag.StringVar(&testPath, "chrome", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "path to chrome")
3131
flag.StringVar(&testDir, "dir", "C:\\temp\\gcd\\", "user directory")
3232
case "darwin":
3333
flag.StringVar(&testPath, "chrome", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "path to chrome")

v2/gcd.go

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import (
4545

4646
var json = jsoniter.ConfigCompatibleWithStandardLibrary
4747

48-
var GCDVERSION = "v2.2.6"
48+
var GCDVERSION = "v2.3.0"
4949

5050
var (
5151
ErrNoTabAvailable = errors.New("no available tab found")
@@ -374,7 +374,12 @@ func (c *Gcd) GetNewTargets(knownIds map[string]struct{}) ([]*ChromeTarget, erro
374374
func (c *Gcd) getConnectableTargets() ([]*TargetInfo, error) {
375375
// some times it takes a while to get results, so retry 4x
376376
for i := 0; i < 4; i++ {
377-
resp, err := http.Get(c.apiEndpoint)
377+
req, err := http.NewRequest("PUT", c.apiEndpoint, nil)
378+
if err != nil {
379+
return nil, err
380+
}
381+
382+
resp, err := http.DefaultClient.Do(req)
378383
if err != nil {
379384
return nil, err
380385
}
@@ -408,7 +413,12 @@ func (c *Gcd) getConnectableTargets() ([]*TargetInfo, error) {
408413

409414
// NewTab a new empty tab, returns the chrome target.
410415
func (c *Gcd) NewTab() (*ChromeTarget, error) {
411-
resp, err := http.Get(c.apiEndpoint + "/new")
416+
req, err := http.NewRequest("PUT", c.apiEndpoint+"/new", nil)
417+
if err != nil {
418+
return nil, err
419+
}
420+
421+
resp, err := http.DefaultClient.Do(req)
412422
if err != nil {
413423
return nil, err
414424
}
@@ -427,30 +437,19 @@ func (c *Gcd) NewTab() (*ChromeTarget, error) {
427437
return openChromeTarget(c, tabTarget, c.messageObserver)
428438
}
429439

430-
// GetFirstTab returns the first tab created, to be called when
431-
// first started, otherwise you will get a random tab returned.
432-
func (c *Gcd) GetFirstTab() (*ChromeTarget, error) {
433-
connectableTargets, err := c.getConnectableTargets()
434-
if err != nil {
435-
return nil, err
436-
}
437-
438-
for _, tabTarget := range connectableTargets {
439-
if tabTarget.Type == "page" {
440-
return openChromeTarget(c, tabTarget, c.messageObserver)
441-
}
442-
}
443-
return nil, ErrNoTabAvailable
444-
}
445-
446440
// GetRevision of chrome
447441
func (c *Gcd) GetRevision() string {
448442
return gcdapi.CHROME_VERSION
449443
}
450444

451445
// CloseTab closes the target tab.
452446
func (c *Gcd) CloseTab(target *ChromeTarget) error {
453-
resp, err := http.Get(fmt.Sprintf("%s/close/%s", c.apiEndpoint, target.Target.Id))
447+
req, err := http.NewRequest("PUT", fmt.Sprintf("%s/close/%s", c.apiEndpoint, target.Target.Id), nil)
448+
if err != nil {
449+
return err
450+
}
451+
452+
resp, err := http.DefaultClient.Do(req)
454453
if err != nil {
455454
return err
456455
}
@@ -461,7 +460,12 @@ func (c *Gcd) CloseTab(target *ChromeTarget) error {
461460

462461
// ActivateTab (focus) the tab.
463462
func (c *Gcd) ActivateTab(target *ChromeTarget) error {
464-
resp, err := http.Get(fmt.Sprintf("%s/activate/%s", c.apiEndpoint, target.Target.Id))
463+
req, err := http.NewRequest("PUT", fmt.Sprintf("%s/activate/%s", c.apiEndpoint, target.Target.Id), nil)
464+
if err != nil {
465+
return err
466+
}
467+
468+
resp, err := http.DefaultClient.Do(req)
465469
if err != nil {
466470
return err
467471
}

v2/gcd_test.go

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -83,13 +83,25 @@ func TestGetPages(t *testing.T) {
8383
testDefaultStartup(t)
8484
defer debugger.ExitProcess()
8585

86+
newTab, err := debugger.NewTab()
87+
if err != nil {
88+
t.Fatalf("error creating tab: %s\n", err)
89+
}
90+
8691
targets, err := debugger.GetTargets()
8792
if err != nil {
8893
t.Fatalf("error getting targets: %s\n", err)
8994
}
95+
9096
if len(targets) <= 0 {
9197
t.Fatalf("invalid number of targets, got: %d\n", len(targets))
9298
}
99+
100+
err = debugger.CloseTab(newTab)
101+
if err != nil {
102+
t.Fatalf("error CloseTab: %s\n", err)
103+
}
104+
93105
t.Logf("page: %s\n", targets[0].Target.Url)
94106
}
95107

@@ -529,7 +541,7 @@ func TestContextCancel(t *testing.T) {
529541
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
530542
defer cancel()
531543

532-
target, err := debugger.GetFirstTab()
544+
target, err := debugger.NewTab()
533545
if err != nil {
534546
t.Fatalf("error getting first tab")
535547
}
@@ -605,19 +617,10 @@ func TestNetworkIntercept(t *testing.T) {
605617
<-doneCh
606618
}
607619

608-
func TestGetFirstTab(t *testing.T) {
609-
testDefaultStartup(t)
610-
defer debugger.ExitProcess()
611-
_, err := debugger.GetFirstTab()
612-
if err != nil {
613-
t.Fatalf("error getting first tab: %v\n", err)
614-
}
615-
}
616-
617620
func TestCloseTab(t *testing.T) {
618621
testDefaultStartup(t)
619622
defer debugger.ExitProcess()
620-
target, err := debugger.GetFirstTab()
623+
target, err := debugger.NewTab()
621624
if err != nil {
622625
t.Fatalf("error getting first tab: %v\n", err)
623626
}
@@ -638,9 +641,9 @@ func TestCustomLogger(t *testing.T) {
638641
customLogger := &testLogger{}
639642
testDefaultStartup(t, WithLogger(customLogger), WithEventDebugging())
640643
defer debugger.ExitProcess()
641-
tab, err := debugger.GetFirstTab()
644+
tab, err := debugger.NewTab()
642645
if err != nil {
643-
t.Fatalf("error getting first tab: %v\n", err)
646+
t.Fatalf("error getting new tab: %v\n", err)
644647
}
645648

646649
if _, err = tab.Page.Enable(context.TODO()); err != nil {

v2/gcdapi/accessibility.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ type AccessibilityGetPartialAXTreeParams struct {
102102
BackendNodeId int `json:"backendNodeId,omitempty"`
103103
// JavaScript object id of the node wrapper to get the partial accessibility tree for.
104104
ObjectId string `json:"objectId,omitempty"`
105-
// Whether to fetch this nodes ancestors, siblings and children. Defaults to true.
105+
// Whether to fetch this node's ancestors, siblings and children. Defaults to true.
106106
FetchRelatives bool `json:"fetchRelatives,omitempty"`
107107
}
108108

@@ -142,7 +142,7 @@ func (c *Accessibility) GetPartialAXTreeWithParams(ctx context.Context, v *Acces
142142
// nodeId - Identifier of the node to get the partial accessibility tree for.
143143
// backendNodeId - Identifier of the backend node to get the partial accessibility tree for.
144144
// objectId - JavaScript object id of the node wrapper to get the partial accessibility tree for.
145-
// fetchRelatives - Whether to fetch this nodes ancestors, siblings and children. Defaults to true.
145+
// fetchRelatives - Whether to fetch this node's ancestors, siblings and children. Defaults to true.
146146
// Returns - nodes - The `Accessibility.AXNode` for this DOM node, if it exists, plus its ancestors, siblings and children, if requested.
147147
func (c *Accessibility) GetPartialAXTree(ctx context.Context, nodeId int, backendNodeId int, objectId string, fetchRelatives bool) ([]*AccessibilityAXNode, error) {
148148
var v AccessibilityGetPartialAXTreeParams

v2/gcdapi/audits.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ type AuditsCookieIssueDetails struct {
3232
Cookie *AuditsAffectedCookie `json:"cookie,omitempty"` // If AffectedCookie is not set then rawCookieLine contains the raw Set-Cookie header string. This hints at a problem where the cookie line is syntactically or semantically malformed in a way that no valid cookie could be created.
3333
RawCookieLine string `json:"rawCookieLine,omitempty"` //
3434
CookieWarningReasons []string `json:"cookieWarningReasons"` // enum values: WarnSameSiteUnspecifiedCrossSiteContext, WarnSameSiteNoneInsecure, WarnSameSiteUnspecifiedLaxAllowUnsafe, WarnSameSiteStrictLaxDowngradeStrict, WarnSameSiteStrictCrossDowngradeStrict, WarnSameSiteStrictCrossDowngradeLax, WarnSameSiteLaxCrossDowngradeStrict, WarnSameSiteLaxCrossDowngradeLax, WarnAttributeValueExceedsMaxSize, WarnDomainNonASCII
35-
CookieExclusionReasons []string `json:"cookieExclusionReasons"` // enum values: ExcludeSameSiteUnspecifiedTreatedAsLax, ExcludeSameSiteNoneInsecure, ExcludeSameSiteLax, ExcludeSameSiteStrict, ExcludeInvalidSameParty, ExcludeSamePartyCrossPartyContext, ExcludeDomainNonASCII
35+
CookieExclusionReasons []string `json:"cookieExclusionReasons"` // enum values: ExcludeSameSiteUnspecifiedTreatedAsLax, ExcludeSameSiteNoneInsecure, ExcludeSameSiteLax, ExcludeSameSiteStrict, ExcludeInvalidSameParty, ExcludeSamePartyCrossPartyContext, ExcludeDomainNonASCII, ExcludeThirdPartyCookieBlockedInFirstPartySet
3636
Operation string `json:"operation"` // Optionally identifies the site-for-cookies and the cookie url, which may be used by the front-end as additional context. enum values: SetCookie, ReadCookie
3737
SiteForCookies string `json:"siteForCookies,omitempty"` //
3838
CookieUrl string `json:"cookieUrl,omitempty"` //
@@ -123,7 +123,7 @@ type AuditsCorsIssueDetails struct {
123123

124124
// Details for issues around "Attribution Reporting API" usage. Explainer: https://github.com/WICG/attribution-reporting-api
125125
type AuditsAttributionReportingIssueDetails struct {
126-
ViolationType string `json:"violationType"` // enum values: PermissionPolicyDisabled, UntrustworthyReportingOrigin, InsecureContext, InvalidHeader, InvalidRegisterTriggerHeader, InvalidEligibleHeader, TooManyConcurrentRequests, SourceAndTriggerHeaders, SourceIgnored, TriggerIgnored
126+
ViolationType string `json:"violationType"` // enum values: PermissionPolicyDisabled, UntrustworthyReportingOrigin, InsecureContext, InvalidHeader, InvalidRegisterTriggerHeader, InvalidEligibleHeader, TooManyConcurrentRequests, SourceAndTriggerHeaders, SourceIgnored, TriggerIgnored, OsSourceIgnored, OsTriggerIgnored, InvalidRegisterOsSourceHeader, InvalidRegisterOsTriggerHeader, WebAndOsHeaders
127127
Request *AuditsAffectedRequest `json:"request,omitempty"` //
128128
ViolatingNodeId int `json:"violatingNodeId,omitempty"` //
129129
InvalidParameter string `json:"invalidParameter,omitempty"` //
@@ -146,20 +146,21 @@ type AuditsNavigatorUserAgentIssueDetails struct {
146146

147147
// Depending on the concrete errorType, different properties are set.
148148
type AuditsGenericIssueDetails struct {
149-
ErrorType string `json:"errorType"` // Issues with the same errorType are aggregated in the frontend. enum values: CrossOriginPortalPostMessageError
150-
FrameId string `json:"frameId,omitempty"` //
149+
ErrorType string `json:"errorType"` // Issues with the same errorType are aggregated in the frontend. enum values: CrossOriginPortalPostMessageError, FormLabelForNameError, FormDuplicateIdForInputError, FormInputWithNoLabelError, FormAutocompleteAttributeEmptyError, FormEmptyIdAndNameAttributesForInputError, FormAriaLabelledByToNonExistingId, FormInputAssignedAutocompleteValueToIdOrNameAttributeError, FormLabelHasNeitherForNorNestedInput, FormLabelForMatchesNonExistingIdError
150+
FrameId string `json:"frameId,omitempty"` //
151+
ViolatingNodeId int `json:"violatingNodeId,omitempty"` //
151152
}
152153

153154
// This issue tracks information needed to print a deprecation message. https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/frame/third_party/blink/renderer/core/frame/deprecation/README.md
154155
type AuditsDeprecationIssueDetails struct {
155156
AffectedFrame *AuditsAffectedFrame `json:"affectedFrame,omitempty"` //
156157
SourceCodeLocation *AuditsSourceCodeLocation `json:"sourceCodeLocation"` //
157-
Type string `json:"type"` // enum values: AuthorizationCoveredByWildcard, CanRequestURLHTTPContainingNewline, ChromeLoadTimesConnectionInfo, ChromeLoadTimesFirstPaintAfterLoadTime, ChromeLoadTimesWasAlternateProtocolAvailable, CookieWithTruncatingChar, CrossOriginAccessBasedOnDocumentDomain, CrossOriginWindowAlert, CrossOriginWindowConfirm, CSSSelectorInternalMediaControlsOverlayCastButton, DeprecationExample, DocumentDomainSettingWithoutOriginAgentClusterHeader, EventPath, ExpectCTHeader, GeolocationInsecureOrigin, GeolocationInsecureOriginDeprecatedNotRemoved, GetUserMediaInsecureOrigin, HostCandidateAttributeGetter, IdentityInCanMakePaymentEvent, InsecurePrivateNetworkSubresourceRequest, LegacyConstraintGoogIPv6, LocalCSSFileExtensionRejected, MediaSourceAbortRemove, MediaSourceDurationTruncatingBuffered, NavigateEventRestoreScroll, NavigateEventTransitionWhile, NoSysexWebMIDIWithoutPermission, NotificationInsecureOrigin, NotificationPermissionRequestedIframe, ObsoleteWebRtcCipherSuite, OpenWebDatabaseInsecureContext, OverflowVisibleOnReplacedElement, PersistentQuotaType, PictureSourceSrc, PrefixedCancelAnimationFrame, PrefixedRequestAnimationFrame, PrefixedStorageInfo, PrefixedVideoDisplayingFullscreen, PrefixedVideoEnterFullscreen, PrefixedVideoEnterFullScreen, PrefixedVideoExitFullscreen, PrefixedVideoExitFullScreen, PrefixedVideoSupportsFullscreen, RangeExpand, RequestedSubresourceWithEmbeddedCredentials, RTCConstraintEnableDtlsSrtpFalse, RTCConstraintEnableDtlsSrtpTrue, RTCPeerConnectionComplexPlanBSdpUsingDefaultSdpSemantics, RTCPeerConnectionSdpSemanticsPlanB, RtcpMuxPolicyNegotiate, SharedArrayBufferConstructedWithoutIsolation, TextToSpeech_DisallowedByAutoplay, V8SharedArrayBufferConstructedInExtensionWithoutIsolation, XHRJSONEncodingDetection, XMLHttpRequestSynchronousInNonWorkerOutsideBeforeUnload, XRSupportsSession
158+
Type string `json:"type"` // One of the deprecation names from third_party/blink/renderer/core/frame/deprecation/deprecation.json5
158159
}
159160

160161
// No Description.
161162
type AuditsFederatedAuthRequestIssueDetails struct {
162-
FederatedAuthRequestIssueReason string `json:"federatedAuthRequestIssueReason"` // enum values: ShouldEmbargo, TooManyRequests, ManifestListHttpNotFound, ManifestListNoResponse, ManifestListInvalidResponse, ManifestNotInManifestList, ManifestListTooBig, ManifestHttpNotFound, ManifestNoResponse, ManifestInvalidResponse, ClientMetadataHttpNotFound, ClientMetadataNoResponse, ClientMetadataInvalidResponse, DisabledInSettings, ErrorFetchingSignin, InvalidSigninResponse, AccountsHttpNotFound, AccountsNoResponse, AccountsInvalidResponse, IdTokenHttpNotFound, IdTokenNoResponse, IdTokenInvalidResponse, IdTokenInvalidRequest, ErrorIdToken, Canceled, RpPageNotVisible
163+
FederatedAuthRequestIssueReason string `json:"federatedAuthRequestIssueReason"` // enum values: ShouldEmbargo, TooManyRequests, WellKnownHttpNotFound, WellKnownNoResponse, WellKnownInvalidResponse, WellKnownListEmpty, ConfigNotInWellKnown, WellKnownTooBig, ConfigHttpNotFound, ConfigNoResponse, ConfigInvalidResponse, ClientMetadataHttpNotFound, ClientMetadataNoResponse, ClientMetadataInvalidResponse, DisabledInSettings, ErrorFetchingSignin, InvalidSigninResponse, AccountsHttpNotFound, AccountsNoResponse, AccountsInvalidResponse, AccountsListEmpty, IdTokenHttpNotFound, IdTokenNoResponse, IdTokenInvalidResponse, IdTokenInvalidRequest, ErrorIdToken, Canceled, RpPageNotVisible
163164
}
164165

165166
// This issue tracks client hints related issues. It's used to deprecate old features, encourage the use of new ones, and provide general guidance.

v2/gcdapi/backgroundservice.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ type BackgroundServiceBackgroundServiceEvent struct {
2424
EventName string `json:"eventName"` // A description of the event.
2525
InstanceId string `json:"instanceId"` // An identifier that groups related events together.
2626
EventMetadata []*BackgroundServiceEventMetadata `json:"eventMetadata"` // A list of event-specific information.
27+
StorageKey string `json:"storageKey"` // Storage key this event belongs to.
2728
}
2829

2930
// Called when the recording state for the service has been updated.

0 commit comments

Comments
 (0)