Skip to content

Browser and navigation functions#

Functions that wait for the page to load, wait for requests, responses and downloaded files, navigate to other pages, read browser information, resize the window, scroll the page, and open, switch and close tabs.

WaitForLoading#

Waits until the current tab finishes loading. Call it right after every page change (Navigate, clicking a link, switching tabs).

Syntax
await WaitForLoading(timeout=0);
Parameters
Name Description
timeout Maximum number of seconds to wait. The default 0 means wait forever, so set a timeout for pages you do not control, to keep the macro from hanging when a page never finishes loading.
Returns

true when the page has finished loading, false when timeout runs out and the page is still loading, null when there is no tab.

Example
1
2
3
4
await Navigate("https://9hits.com/");
// wait up to 30 seconds
const ok = await WaitForLoading(30);
if (!ok) Log("The page is taking too long to load");

Note

A page that has finished loading may not show all of its content yet, especially a page built with JavaScript. If you need a specific element, also wait for it with WaitForElmtBySelector.

IsLoading#

Tells you whether the current tab is still loading. You should usually use WaitForLoading instead, because WaitForLoading waits by itself, with no loop needed.

Syntax
await IsLoading();
Returns

true while loading, false when loading has finished, null when there is no tab, 0 when the tab state cannot be read. false, null and 0 are all "falsy" values, so compare with true as in the example below.

Example
1
2
3
4
// check every second until the page finishes loading
while (await IsLoading() === true) {
    await Delay(1000);
}

WaitForResponse#

Waits until the current tab receives the response to a request whose URL matches, for example the data a page loads after you click search. Use it instead of a loop that checks the page every second.

Syntax
await WaitForResponse(match, timeout=30, withBody=false);
Parameters
Name Description
match A string that the request URL contains, or a regular expression (RegExp) tested against the whole URL.
timeout Maximum number of seconds to wait. Default 30.
withBody true to also get the response body. Default false.
Returns

An object {url, status, statusText, mimeType, type} for the first matching response, or null when timeout runs out. When withBody is true, the object also has body (a string) and base64 (true when body is binary data in base64 form); if the body cannot be read, body is null and error is included.

Example
1
2
3
4
5
6
7
8
// start waiting BEFORE clicking, then await the result
const p = WaitForResponse("/api/search", 30, true);
await ClickBySelector("button[type=submit]");
const res = await p;
if (res && res.status === 200) {
    const data = JSON.parse(res.body);
    Log("Result count:", data.items.length);
}

Note

Always call the function before the action that triggers the request (click, typing, Navigate) and only await it after that action, as in the example above. If you start waiting after the click, the response may already have arrived. Requests sent by an iframe from another website are not counted.

WaitForRequest#

Waits until the current tab sends a request whose URL matches, so you can see what the page sent: the method, the headers and the attached data.

Syntax
await WaitForRequest(match, timeout=30);
Parameters
Name Description
match A string that the request URL contains, or a regular expression (RegExp) tested against the whole URL.
timeout Maximum number of seconds to wait. Default 30.
Returns

An object {url, method, headers, postData, type} for the first matching request, or null when timeout runs out. postData is null when the request sends no data.

Example
1
2
3
4
const p = WaitForRequest(/\/api\/login/);
await ClickBySelector("button[type=submit]");
const req = await p;
if (req) Log(req.method, req.postData);

WaitForDownload#

Waits for the next file download to finish and tells you where the file was saved.

Syntax
await WaitForDownload(timeout=60);
Parameters
Name Description
timeout Maximum number of seconds to wait. Default 60.
Returns

An object {id, url, filename, state, bytes, mime, error} for the first download that starts after the call, once that download has finished or been interrupted. filename is the full path of the file on your computer. state is "complete" or "interrupted"; when the download is interrupted, error gives the reason. null when timeout runs out.

Example
1
2
3
4
5
// start waiting before clicking the download button
const p = WaitForDownload(120);
await ClickBySelector("a.export-csv");
const file = await p;
if (file && file.state === "complete") Log("Saved:", file.filename);

Note

The function watches every download in the browser, not just those from the current tab. When the browser blocks a download, no download takes place and the function returns null after timeout.

Opens a URL in the current tab. The function does not wait for the page to load, so call WaitForLoading right after it.

Syntax
await Navigate(url, referrer);
Parameters
Name Description
url Full URL of the page to open, including https://, for example "https://9hits.com/".
referrer Referring page to send along (optional), so the target page sees that you came from it. Leave it empty to send none.
Examples
1
2
3
4
5
6
7
// open the page, then wait for it to load
await Navigate("https://google.com/");
await WaitForLoading(30);

// open 9hits.com as if coming from google.com
await Navigate("https://9hits.com/", "https://google.com/");
await WaitForLoading(30);

GetUrl#

Returns the tab's current URL. Use it to find out where the page went after a click or a redirect.

Syntax
await GetUrl();
Returns

A URL string, or null when there is no tab.

Example
1
2
3
4
5
const url = await GetUrl();
Log(url);

// if the page redirected to the login page, click the login button
if (url?.includes("/login")) await ClickBySelector("#login");

GetHtml#

Returns the current HTML of the whole page, after the page's JavaScript has run (not the original source from the server). Real pages are often hundreds of KB; if you only need part of it, reading it with EvalScript is leaner.

Syntax
await GetHtml(frameSearch="", frameSearchType="");
Parameters
Name Description
frameSearch Has no effect yet: the function always reads the main page. To read the HTML inside an iframe, use EvalScript as in the example below.
frameSearchType Has no effect yet, like frameSearch.
Returns

An HTML string, or "" when the HTML cannot be read.

Examples
1
2
3
4
5
6
const html = await GetHtml();
Log(html.length);

// HTML of the iframe whose URL contains "checkout"
const r = await EvalScript("document.documentElement.outerHTML", "checkout", "src-contains");
const frameHtml = r.result || "";

GetUserAgent#

Returns the session's User-Agent string. The function is synchronous, so no await is needed.

Syntax
GetUserAgent();
Returns

The User-Agent string.

Example
const ua = GetUserAgent();
Log(ua);

IsMobile#

Tells you whether the session is set up as a mobile device. The function reads the session's settings; it does not tell you whether the page shows a mobile layout. The function is synchronous, so no await is needed.

Syntax
IsMobile();
Returns

true or false.

Example
1
2
3
// tap on mobile, click on desktop
if (IsMobile()) await SendTouch([{x: 200, y: 400}]);
else await ClickBySelector("#go");

IsHideBrowser#

Tells you whether the session runs with a hidden browser window. A hidden window can still take screenshots of the page as usual. The function is synchronous, so no await is needed.

Syntax
IsHideBrowser();
Returns

true or false.

Example
const hidden = IsHideBrowser();
Log(hidden ? "The window is hidden" : "The window is visible");

GetWindowSize#

Returns the size of the whole browser window, including the frame and the toolbar. For the page's visible area, use GetBrowserSize.

Syntax
await GetWindowSize();
Returns

An object {width, height} in pixels, or {} when the size cannot be read (then width is undefined).

Example
1
2
3
const size = await GetWindowSize();
// size = {width: 1000, height: 800}
if (size.width === undefined) Log("Could not read the window size");

GetBrowserSize#

Returns the size of the page's visible area (viewport) in the current tab, that is the part of the page you can see, without the window frame.

Syntax
await GetBrowserSize();
Returns

An object {width, height} in pixels; both are 0 when the size cannot be read.

Example
1
2
3
4
const s = await GetBrowserSize();
// s = {width: 984, height: 690}
// scroll down exactly one screen
await ScrollTo(0, s.height);

ResizeTo#

Resizes the browser window. This is the whole window, so the page's visible area ends up slightly smaller than the numbers you pass (by the frame and the toolbar).

Syntax
await ResizeTo(width, height);
Parameters
Name Description
width New window width, in pixels. Must be a non-negative number: the string "800" is not accepted.
height New window height, in pixels. Must be a non-negative number.
Returns

true when the resize request has been sent, false when there is no tab or a parameter is invalid. true does not guarantee that the window now has that exact size; to be sure, read it back with GetWindowSize.

Example
1
2
3
4
await ResizeTo(1280, 800);
// read back the actual size
const size = await GetWindowSize();
Log(size.width, size.height);

MoveTo#

Moves the browser window to the coordinates x, y on the screen. The function does not scroll the page; to scroll the page, use ScrollTo.

Syntax
await MoveTo(x, y);
Parameters
Name Description
x Horizontal screen coordinate of the window's left edge, in pixels. Must be a number; negative values are allowed.
y Vertical screen coordinate of the window's top edge, in pixels. Must be a number; negative values are allowed.
Returns

true when the request has been sent, false when there is no tab or a parameter is not a number.

Example
// move the window to the top-left corner of the screen
await MoveTo(0, 0);

ScrollTo#

Scrolls the page to the position X, Y measured from the top of the page, so calling ScrollTo(0, 500) twice leaves you at the same place.

Syntax
await ScrollTo(X, Y, smooth=false);
Parameters
Name Description
X Horizontal position to scroll to, in pixels from the left edge of the page. Must be a number.
Y Vertical position to scroll to, in pixels from the top of the page. Must be a number.
smooth true to scroll smoothly, false to jump straight to the position. Default false.
Returns

false when X or Y is not a number. Otherwise the same kind of object as EvalScript: {error} when the page could not run the scroll, or {result} with no useful value when it could.

Examples
1
2
3
4
5
6
// scroll down to 1000px from the top of the page
await ScrollTo(0, 1000);

// scroll smoothly back to the top, then wait for the scroll animation to finish
await ScrollTo(0, 0, true);
await Delay(400, 900);

Note

The page scrolls right after the function returns, and smooth scrolling takes extra time, so wait a moment with Delay before you measure element coordinates. If the page only reacts to the mouse wheel, use SendMouseWheel.

TabCount#

Returns the number of open tabs. Use it to find out whether the page just opened another tab or a popup.

Syntax
await TabCount();
Returns

The number of open tabs, or 0 when it cannot be read.

Example
const tabs = await TabCount();
if (tabs > 1) Log("A popup just opened");

GetTabs#

Lists the open tabs, with their ids so you can switch to or close exactly the tab you want.

Syntax
await GetTabs();
Returns

An array of objects {id, url, title, active, windowId, target}. target is true on the tab that the macro commands are running on. An empty array when the tabs cannot be read.

Example
1
2
3
4
5
6
const tabs = await GetTabs();
for (const t of tabs) Log(t.id, t.url);

// switch to the shop site's tab, if there is one
const shop = tabs.find(t => t.url.includes("shop."));
if (shop) await TabFocus({id: shop.id});

TabFocus#

Switches to another tab and brings that tab's window to the front; the macro commands after it run on this tab. The function cannot be used in Popup macro.

Syntax
await TabFocus(query);
Parameters
Name Description
query Tab number (1 is the first tab), or a string to pick the first tab whose URL contains that string. Put ! in front of the string to pick the first tab whose URL does not contain it, which is handy when you want to leave the current page. Or {id} to pick exactly the tab with an id from GetTabs or NewTab: tab numbers change when tabs are opened or closed, ids do not.
Returns

true when the tab is found and the switch works, false when no tab matches or when the function is called in Popup macro.

Examples
// the page just opened another tab: switch to the 2nd tab and wait for it to load
if (await TabCount() > 1) {
    await TabFocus(2);
    await WaitForLoading(30);
    Log(await GetUrl());
}

await TabFocus("facebook.com");  // first tab whose URL contains facebook.com
await TabFocus("!facebook.com"); // first tab whose URL does not contain facebook.com
await TabFocus(1);               // back to the first tab

// by id, which stays correct when the number of tabs changes
const tabs = await GetTabs();
await TabFocus({id: tabs[0].id});

NewTab #

Opens a new tab in the current window. By default, the macro commands after it run on the new tab.

Syntax
await NewTab(url="", focus=true);
Parameters
Name Description
url The page to open. Leave it empty to open the New Tab page, which you can still control like any other page. Default "".
focus true: brings the new tab to the front and runs the following commands on it, like TabFocus. false: opens it in the background, and the following commands still run on the old tab. Default true.
Returns

The new tab's id (a number), or false when the tab cannot be opened, with the reason written to the log. In 9Hits campaigns the function is blocked and returns {error: "Blocked"}.

Example
1
2
3
4
5
const id = await NewTab("https://9hits.com/");
await WaitForLoading(30);
Log(await GetUrl());
// close the tab you just opened; the following commands go back to the remaining tab
await CloseTab(id);

Note

The function does not wait for the page to load, so call WaitForLoading after it. In Popup macro, the new tab does not replace the tab the popup macro is running on.

CloseTab #

Closes a tab.

Syntax
await CloseTab(target="");
Parameters
Name Description
target The tab's id (from GetTabs or NewTab), or a string to close the first tab whose URL contains that string. Leave it empty for the tab the macro commands are running on. Default "".
Returns

true when the tab is closed, false when no tab matches or it is the last tab; the reason is written to the log. In 9Hits campaigns the function is blocked and returns {error: "Blocked"}.

Example
// close the ad popup that just opened
await CloseTab("ads.example.com");

Note

The function does not close the last tab, because closing it would close the browser. If you close the tab the macro commands are running on, the following commands run on the tab the window is currently showing.