github.com/bazelbuild/rules_webtesting@v0.2.0/go/wtl/proxy/driverhub/quithandler/quit_handler.go (about)

     1  // Copyright 2017 Google Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package quithandler checks if a window close command is closing the last window and treats it
    16  // as a quit if it is.
    17  package quithandler
    18  
    19  import (
    20  	"context"
    21  	"net/http"
    22  
    23  	"github.com/bazelbuild/rules_webtesting/go/metadata/capabilities"
    24  	"github.com/bazelbuild/rules_webtesting/go/wtl/proxy/driverhub"
    25  )
    26  
    27  // ProviderFunc provides a handler for quit and close commands that end the session within the environment when the browser exits.
    28  func ProviderFunc(session *driverhub.WebDriverSession, _ *capabilities.Capabilities, base driverhub.HandlerFunc) (driverhub.HandlerFunc, bool) {
    29  	return func(ctx context.Context, rq driverhub.Request) (driverhub.Response, error) {
    30  		// If quit command, then quit.
    31  		if rq.Method == http.MethodDelete && len(rq.Path) == 0 {
    32  			return session.Quit(ctx, rq)
    33  		}
    34  
    35  		// If not window close command, then forward as normal
    36  		if rq.Method != http.MethodDelete || len(rq.Path) != 1 || rq.Path[0] != "window" {
    37  			return base(ctx, rq)
    38  		}
    39  
    40  		// If closing last window, then quit.
    41  		if windows, err := session.WindowHandles(ctx); err != nil {
    42  			return driverhub.ResponseFromError(err)
    43  		} else if len(windows) == 1 {
    44  			return session.Quit(ctx, rq)
    45  		}
    46  
    47  		// Otherwise forward the close window
    48  		return base(ctx, rq)
    49  	}, true
    50  }