marionette

package module
v0.0.0-...-7adfa47 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2023 License: MIT Imports: 14 Imported by: 0

README

Go Reference Build Status Coverage Status Go Report Card License

Marionette Go client

Mozilla's Gecko Marionette client in Golang.

Originally forked from njasm/marionette_client.

Work-in-progress. Expect API breakage.

What is Marionette

"Marionette is an automation driver for Mozilla's Gecko engine. It can remotely control either the UI, or the internal JavaScript of a Gecko platform, such as Firefox. It can control both the chrome (i.e. menus and functions) or the content (the webpage loaded inside the browsing context), giving a high level of control and ability to replicate user actions. In addition to performing actions on the browser, Marionette can also read the properties and attributes of the DOM.

If this sounds similar to Selenium/WebDriver then you're correct! Marionette shares much of the same ethos and API as Selenium/WebDriver, with additional commands to interact with Gecko's chrome interface. Its goal is to replicate what Selenium does for web content: to enable the tester to have the ability to send commands to remotely control a user agent."

Resources

https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette

https://w3c.github.io/webdriver/webdriver-spec.html

Examples

Incomplete list. Check the tests for more examples.

Instantiate the client
client := NewClient()
// this are the default marionette values for hostname, and port 
client.Connect("", 0)
// let marionette generate the Session ID with it's default Capabilities
client.NewSession("", nil) 
	
Navigate to page
client.Navigate("http://www.google.com/")
Change Contexts
client.SetContext(Context(CHROME))
// or
client.SetContext(Context(CONTENT))
	
Find Element
element, err := client.FindElement(By(ID), "html-element-id-attribute")
if err != nil {
	// handle your errors
}

// else
println(element.Id())
println(element.Enabled())
println(element.Selected())
println(element.Displayed())
println(element.TagName())
println(element.Text())
println(element.Attribute("id"))
println(element.Property("id"))
println(element.CssValue("text-decoration"))
	
// width, height, x and y
rect, err := element.Rect()
if err != nil {
    // handle your errors
}

fmt.Printf("%#v", rect)
	
// size
w, h, err := element.Size()
if err != nil {
	// handle your errors
}

fmt.Printf("width: %f, height: %f", w, h)

//location
x, y, err := element.Location()
if err != nil {
    // handle your errors
}

fmt.Printf("x: %v, y: %v", x, y)
Find Elements
collection, err := element.FindElements(By(TAG_NAME), "li")
if err != nil {
	// handle your errors
}

// else
for var e := range collection {
	println(e.Id())
   	println(e.Enabled())
   	println(e.Selected())
   	println(e.Displayed())
   	println(e.TagName())
   	println(e.Text())
   	println(e.Attribute("id"))
   	println(e.CssValue("text-decoration"))
   	e.Click()
}
Execute JS Script
script := "function mySum(a, b) { return a + b; }; return mySum(arguments[0], arguments[1]);"
args := []int{1, 3} // arguments to be passed to the function
timeout := 1000     // milliseconds
sandbox := false    // new Sandbox
r, err := client.ExecuteScript(script, args, timeout, sandbox)
if err == nil {
    println(r.Value) // 4 
}
Wait(), Until() Expected condition is true.
client.Navigate("http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get")

timeout := time.Duration(10) * time.Second
condition := ElementIsPresent(By(ID), "stackH")
ok, webElement, err := Wait(client).For(timeout).Until(condition)

if !ok {
	log.Printf("%#v", err)
	// do your error stuff
	return
}

// cool, we've the element, let's click on it!
webElement.Click()

Documentation

Index

Constants

View Source
const (
	MARIONETTE_PROTOCOL_V3 = 3
	WEBDRIVER_ELEMENT_KEY  = "element-6066-11e4-a52e-4f735466cecf"
)

Variables

View Source
var RunningInDebugMode = false

Functions

func Attribute

func Attribute[T any](e *WebElement, name string) (T, error)

func ElementIsNotPresent

func ElementIsNotPresent(by By, value string) func(f Finder) (bool, *WebElement, error)

func ElementIsPresent

func ElementIsPresent(by By, value string) func(f Finder) (bool, *WebElement, error)

func Property

func Property[T any](e *WebElement, name string) (T, error)

Types

type By

type By int

By is a strategy type to find elements in the DOM.

const (
	ID By = 1 + iota
	NAME
	CLASS_NAME
	TAG_NAME
	CSS_SELECTOR
	LINK_TEXT
	PARTIAL_LINK_TEXT
	XPATH
	ANON
	ANON_ATTRIBUTE
)

:param method: The method to use to locate the element; one of:

"id", "name", "class name", "tag name", "css selector",
"link text", "partial link text", "xpath", "anon" and "anon
attribute". Note that the "name", "link text" and "partial
link test" methods are not supported in the chrome DOM.

:param target: The target of the search. For example, if method =

"tag", target might equal "div".  If method = "id", target would
be an element id.

:param id: If specified, search for elements only inside the element

with the specified id.

"""

func (By) String

func (b By) String() string

String returns the value name of the strategy ("css selector", "link text", ...).

type Capabilities

type Capabilities struct {
	BrowserName                   string
	BrowserVersion                string
	PlatformName                  string
	PlatformVersion               string
	SpecificationLevel            uint
	RaisesAccessibilityExceptions bool
	Rotatable                     bool
	AcceptSslCerts                bool
	TakesElementScreenshot        bool
	TakesScreenshot               bool
	Proxy                         any
	Platform                      string
	XULappId                      string
	AppBuildId                    string
	Device                        string
	Version                       string
	Command_id                    uint32
}

type Client

type Client struct {
	SessionId    string
	Capabilities Capabilities
	// contains filtered or unexported fields
}

func NewClient

func NewClient() *Client

func (*Client) AcceptAlert

func (c *Client) AcceptAlert() error

AcceptAlert accepts the dialog - like clicking Ok/Yes

func (*Client) AddCookie

func (c *Client) AddCookie(cookie Cookie) (*Response, error)

AddCookie Adds a cookie

func (*Client) Back

func (c *Client) Back() error

Back go back in navigation history

func (*Client) CloseChromeWindow

func (c *Client) CloseChromeWindow() (*Response, error)

CloseChromeWindow closes the currently selected chrome window.

If it is the last window currently open, the chrome window will not be closed to prevent a shutdown of Firefox. Instead the returned list of chrome window handles is empty.

return []string Unique chrome window handles of remaining chrome windows.

error NoSuchWindowError Top-level browsing context has been discarded.

func (*Client) CloseWindow

func (c *Client) CloseWindow() (*Response, error)

CloseWindow closes current window.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, addr string) error

func (*Client) Context

func (c *Client) Context() (*Response, error)

Context Gets the context of the server, either "chrome" or "content".

func (*Client) DeleteAllCookies

func (c *Client) DeleteAllCookies() error

DeleteAllCookies Delete all cookies

func (*Client) DeleteCookie

func (c *Client) DeleteCookie(name string) (error, error)

DeleteCookie Deletes cookie by name

func (*Client) DeleteSession

func (c *Client) DeleteSession() error

DeleteSession Marionette currently only accepts a session id, so if we call delete session can also close the TCP Connection

func (*Client) DismissAlert

func (c *Client) DismissAlert() error

DismissAlert dismisses the dialog - like clicking No/Cancel

func (*Client) DownloadImage

func (c *Client) DownloadImage(ctx context.Context, src string) (image.Image, error)

DownloadImage opens an image URL in the current tab and downloads it.

func (*Client) ExecuteAsyncScript

func (c *Client) ExecuteAsyncScript(script string, args []any, newSandbox bool) (*Response, error)

ExecuteAsyncScript Execute JS Script Async TODO: Add missing arguments/options

func (*Client) ExecuteScript

func (c *Client) ExecuteScript(script string, args []any, timeout time.Duration, newSandbox bool) (*Response, error)

ExecuteScript Execute JS Script

func (*Client) FindElement

func (c *Client) FindElement(by By, value string) (*WebElement, error)

FindElement Find an element using the indicated search strategy.

func (*Client) FindElements

func (c *Client) FindElements(by By, value string) ([]*WebElement, error)

FindElements Find elements using the indicated search strategy.

func (*Client) Forward

func (c *Client) Forward() error

Forward go forward in navigation history

func (*Client) FullscreenWindow

func (c *Client) FullscreenWindow() (rect *WindowRect, err error)

FullscreenWindow Synchronously sets the user agent window to full screen as if the user had done "View > Enter Full Screen"

func (*Client) GetActiveElement

func (c *Client) GetActiveElement() (*WebElement, error)

GetActiveElement Returns the page's active element.

func (*Client) GetCapabilities

func (c *Client) GetCapabilities() (*Capabilities, error)

GetCapabilities informs the client of which WebDriver features are supported by Firefox and Marionette. They are immutable for the length of the session.

func (*Client) GetCookies

func (c *Client) GetCookies() ([]Cookie, error)

GetCookies Get all cookies

func (*Client) GetTimeouts

func (c *Client) GetTimeouts() (map[string]uint, error)

Get Timeouts Get current set timeouts

func (*Client) GetWindowHandle

func (c *Client) GetWindowHandle() (string, error)

GetWindowHandle returns the current window ID

func (*Client) GetWindowHandles

func (c *Client) GetWindowHandles() ([]string, error)

GetWindowHandles return array of window ID currently opened

func (*Client) GetWindowRect

func (c *Client) GetWindowRect() (rect *WindowRect, err error)

GetWindowRect gets window position and size

func (*Client) MaximizeWindow

func (c *Client) MaximizeWindow() (*WindowRect, error)

MaximizeWindow maximizes window.

func (*Client) MinimizeWindow

func (c *Client) MinimizeWindow() (*WindowRect, error)

MinimizeWindow Synchronously minimizes the user agent window as if the user pressed the minimize button.

func (*Client) Navigate

func (c *Client) Navigate(url string) (*Response, error)

Navigate open url

func (*Client) NewSession

func (c *Client) NewSession(sessionId string, cap *Capabilities) (*Response, error)

NewSession create new session

func (*Client) NewWindow

func (c *Client) NewWindow(focus bool, typ string, private bool) (*Response, error)

NewWindow opens a new top-level browsing context window.

param: type string Optional type of the new top-level browsing context. Can be one of `tab` or `window`. Defaults to `tab`.

param: focus bool Optional flag if the new top-level browsing context should be opened in foreground (focused) or background (not focused). Defaults to false.

param: private bool Optional flag, which gets only evaluated for type `window`. True if the new top-level browsing context should be a private window. Defaults to false.

return {"handle": string, "type": string} Handle and type of the new browsing context.

func (*Client) PageSource

func (c *Client) PageSource() (string, error)

PageSource get page source

func (*Client) Quit

func (c *Client) Quit() (*Response, error)

Quit quits the session and request browser process to terminate.

func (*Client) Refresh

func (c *Client) Refresh() error

Refresh the page.

func (*Client) Screenshot

func (c *Client) Screenshot() ([]byte, error)

Screenshot takes a screenshot of the page.

func (*Client) ScreenshotImage

func (c *Client) ScreenshotImage() (image.Image, error)

ScreenshotImage takes a screenshot of the page.

func (*Client) SendAlertText

func (c *Client) SendAlertText(keys string) error

SendAlertText sends text to a dialog

func (*Client) SessionID

func (c *Client) SessionID() string

func (*Client) SetContext

func (c *Client) SetContext(value Context) (*Response, error)

SetContext Sets the context of the subsequent commands to be either "chrome" or "content". Must be one of "chrome" or "content" only.

func (*Client) SetImplicitTimout

func (c *Client) SetImplicitTimout(timeout time.Duration) (*Response, error)

SetImplicitTimout Set timeout for searching for elements.

func (*Client) SetPageLoadTimeout

func (c *Client) SetPageLoadTimeout(timeout time.Duration) (*Response, error)

SetPageLoadTimeout Set timeout for page loading.

func (*Client) SetScriptTimeout

func (c *Client) SetScriptTimeout(timeout time.Duration) (*Response, error)

SetScriptTimeout Set the timeout for asynchronous script execution.

func (*Client) SetTimeouts

func (c *Client) SetTimeouts(data map[string]int) (*Response, error)

SetTimeouts sets timeouts object.

<dl> <dt><code>script</code> (number) <dd>Determines when to interrupt a script that is being evaluates.

<dt><code>pageLoad</code> (number) <dd>Provides the timeout limit used to interrupt navigation of the

browsing context.

<dt><code>implicit</code> (number) <dd>Gives the timeout of when to abort when locating an element. </dl>

func (*Client) SetWindowRect

func (c *Client) SetWindowRect(rect WindowRect) error

SetWindowRect sets window position and size

func (*Client) SwitchToFrame

func (c *Client) SwitchToFrame(by By, value string) error

SwitchToFrame switch to frame - strategies: By(ID), By(NAME) or name only.

func (*Client) SwitchToParentFrame

func (c *Client) SwitchToParentFrame() error

SwitchToParentFrame switch to parent frame

func (*Client) SwitchToWindow

func (c *Client) SwitchToWindow(name string) error

SwitchToWindow switch to specific window.

func (*Client) TextFromAlert

func (c *Client) TextFromAlert() (string, error)

TextFromAlert gets text from the dialog

func (*Client) Title

func (c *Client) Title() (string, error)

Title get title

func (*Client) Transport

func (c *Client) Transport(tr *Transport)

func (*Client) URL

func (c *Client) URL() (string, error)

URL get current url

type Codec

type Codec interface {
	Decoder
	Encoder
}

func NewDecoderEncoder

func NewDecoderEncoder(protoVersion int32) (Codec, error)

type Context

type Context int
const (
	CHROME Context = 1 + iota
	CONTENT
)

func (Context) String

func (c Context) String() string

String returns the value name of the context ("chrome", "content").

type Cookie struct {
	Secure   bool   `json:"secure,omitempty"`
	Expiry   uint   `json:"expiry,omitempty"`
	Domain   string `json:"domain,omitempty"`
	HttpOnly bool   `json:"httpOnly,omitempty"`
	Name     string `json:"name"`
	Path     string `json:"path,omitempty"`
	Value    string `json:"value"`
}

type Decoder

type Decoder interface {
	Decode(buf []byte, r *Response) error
}

type DriverError

type DriverError struct {
	ErrorType  string `json:"Error"`
	Message    string
	Stacktrace *string
}

func (*DriverError) Error

func (e *DriverError) Error() string

func (*DriverError) String

func (e *DriverError) String() string

type ElementRect

type ElementRect struct {
	Point
	Size
}

type Encoder

type Encoder interface {
	Encode(id int, command string, values any) ([]byte, error)
}

type Finder

type Finder interface {
	FindElement(by By, value string) (*WebElement, error)
	FindElements(by By, value string) ([]*WebElement, error)
}
type Navigator interface {
	Navigate(url string) (*Response, error)
	PageSource() (*Response, error)
	Title() (string, error)
	Url() (string, error)
	Refresh() error
	Back() error
	Forward() error
}

type Point

type Point struct {
	X float32
	Y float32
}

type ProtoV3

type ProtoV3 struct{}

func (ProtoV3) Decode

func (e ProtoV3) Decode(buf []byte, r *Response) error

func (ProtoV3) Encode

func (e ProtoV3) Encode(id int, command string, values any) ([]byte, error)

type Response

type Response struct {
	MessageID   int32
	Size        int32
	Value       string
	DriverError *DriverError
}

type Size

type Size struct {
	Width  float64
	Height float64
}

type Transport

type Transport struct {
	ApplicationType    string
	MarionetteProtocol int32
	// contains filtered or unexported fields
}

func (*Transport) Close

func (t *Transport) Close() error

func (*Transport) Connect

func (t *Transport) Connect(ctx context.Context, addr string) error

func (*Transport) MessageID

func (t *Transport) MessageID() int

func (*Transport) Receive

func (t *Transport) Receive() ([]byte, error)

func (*Transport) Send

func (t *Transport) Send(command string, values any) (*Response, error)

func (*Transport) SendAndDecode

func (t *Transport) SendAndDecode(dest any, command string, values any) error

type Waiter

type Waiter struct {
	// contains filtered or unexported fields
}

func Wait

func Wait(f Finder) *Waiter

func (*Waiter) For

func (w *Waiter) For(d time.Duration) *Waiter

func (*Waiter) Until

func (w *Waiter) Until(f func(c Finder) (bool, *WebElement, error)) (bool, *WebElement, error)

type WebElement

type WebElement struct {
	// contains filtered or unexported fields
}

func (*WebElement) Attribute

func (e *WebElement) Attribute(name string) (string, error)

func (*WebElement) Clear

func (e *WebElement) Clear()

func (*WebElement) Click

func (e *WebElement) Click()

func (*WebElement) CssValue

func (e *WebElement) CssValue(property string) (any, error)

func (*WebElement) Displayed

func (e *WebElement) Displayed() bool

func (*WebElement) Enabled

func (e *WebElement) Enabled() bool

func (*WebElement) FindElement

func (e *WebElement) FindElement(by By, value string) (*WebElement, error)

func (*WebElement) FindElements

func (e *WebElement) FindElements(by By, value string) ([]*WebElement, error)

func (*WebElement) GetActiveElement

func (e *WebElement) GetActiveElement() (*WebElement, error)

func (*WebElement) Id

func (e *WebElement) Id() string

func (*WebElement) Location

func (e *WebElement) Location() (*Point, error)

func (*WebElement) Property

func (e *WebElement) Property(name string) (any, error)

func (*WebElement) PropertyFloat

func (e *WebElement) PropertyFloat(name string) (float64, error)

func (*WebElement) PropertyInt

func (e *WebElement) PropertyInt(name string) (int, error)

func (*WebElement) PropertyRaw

func (e *WebElement) PropertyRaw(name string) (json.RawMessage, error)

func (*WebElement) PropertyString

func (e *WebElement) PropertyString(name string) (string, error)

func (*WebElement) Rect

func (e *WebElement) Rect() (*ElementRect, error)

func (*WebElement) Screenshot

func (e *WebElement) Screenshot() ([]byte, error)

func (*WebElement) ScreenshotImage

func (e *WebElement) ScreenshotImage() (image.Image, error)

func (*WebElement) Selected

func (e *WebElement) Selected() bool

func (*WebElement) SendKeys

func (e *WebElement) SendKeys(keys string) error

func (*WebElement) Size

func (e *WebElement) Size() (*Size, error)

func (*WebElement) TagName

func (e *WebElement) TagName() string

func (*WebElement) Text

func (e *WebElement) Text() string

func (*WebElement) UnmarshalJSON

func (e *WebElement) UnmarshalJSON(data []byte) error

type WindowRect

type WindowRect struct {
	X      float64
	Y      float64
	Width  float64
	Height float64
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL