CorvidReference

wix-window

The wix-window module contains functionality that pertains to the current browser window.

To use the window module, import wixWindow from the wix-window module:

   import wixWindow from 'wix-window';

The APIs in wix-window can only be used in front-end code.

Table of Contents

PROPERTIES

?
Store values associated with an object.
browserLocaleGets the locale of the site visitor's browser.
formFactorGets what kind of device is being used to view the page.
localeGets the locale of the current environment.
referrerGets the HTTP referrer header field.
viewModeGets which mode the site is currently being viewed in.

FUNCTIONS

?
Perform actions on an object.
getBoundingRect( )Returns information about the window.
getCurrentGeolocation( )Returns the current geolocation of the user.
getRouterData( )Returns the data that a router passed to the page in its response.
openLightbox( )Opens a lightbox and optionally passes it the given data.
openModal( )Opens a modal window that displays the specified web page.
postMessage( )Sends a message to the page's parent.
scrollBy( )Scrolls the page by a given number of pixels.
scrollTo( )Scrolls the page to a specific location.
trackEvent( )Sends a tracking event to external analytics tools.

OBJECTS

?
Objects used when setting, getting, or calling the properties and methods listed above.
OpenModalOptionsAn object used when opening a modal window.
WindowSizeInfoAn object returned by the getBoundingRect() function that contains information about the window's size, the document's size, and the current scroll position.

Related Content

FAQ

    How do I make my site act differently depending on what device it is being viewed on?
    How do I close a lightbox?
    How do I pass data between a page and a lightbox?
    How does my site interact with a site that embeds it?

browserLocale

Gets the locale of the site visitor's browser.

Description

A locale, also known as an IETF language tag, is an abbreviated code that defines the language, country, and other aspects of the site visitor's browser, such as number format and date format.

Some common locales include:

  • "en-US": English, United States
  • "en-GB": English, British
  • "es-ES": Spanish, Spain
  • "de-DE": German, Germany
  • "ja-JP": Japanese, Japan
  • "fr-CH": French, Switzerland
  • "it-IT": Italian, Italy

Syntax

get browserLocale(): string
TYPE
?
The kind of data the property stores.
string

Examples

Get the locale of a visitor's browser

import wixWindow from 'wix-window';

// ...

let browserLocale = wixWindow.browserLocale;  // "en-US"

formFactor

Gets what kind of device is being used to view the page.

Description

The formFactor property gets one of:

  • "Desktop": When viewed in a desktop browser.
  • "Mobile": When viewed in a mobile browser.
  • "Tablet": When viewed in a tablet browser.

Syntax

get formFactor(): string
TYPE
?
The kind of data the property stores.
string

Examples

Get a device's form factor

import wixWindow from 'wix-window';

// ...

let formFactor = wixWindow.formFactor;  // "Mobile"

locale

Gets the locale of the current environment.

Description

Deprecation note: The locale property is being deprecated. Use the browserLocale property instead.

A locale, also known as an IETF language tag, is an abbreviated code that defines the user's language, country, and other aspects of the user interface such as number format and date format.

Some common locales include:

  • "en-US": English, United States
  • "en-GB": English, British
  • "es-ES": Spanish, Spain
  • "de-DE": German, Germany
  • "ja-JP": Japanese, Japan
  • "fr-CH": French, Switzerland
  • "it-IT": Italian, Italy

Syntax

get locale(): string
TYPE
?
The kind of data the property stores.
string

Examples

Get an environment's locale

import wixWindow from 'wix-window';

// ...

let locale = wixWindow.locale;  // "en-US"

referrer

Gets the HTTP referrer header field.

Description

The referrer is the address of the previous web page that the user was on before arriving at the current page, typically by clicking a link.

Note

When visitors move from page to page within your site, the referrer property does not contain the address of the page the visitor came from. This is because Wix sites are built as single page applications. To get the previous page a visitor was visiting within your site, you can use wix-storage to store the visitor's current page and retrieve the visitor's previous page.

Syntax

get referrer(): string
TYPE
?
The kind of data the property stores.
string

Examples

Get the referrer information

import wixWindow from 'wix-window';

// ...

let referrer = wixWindow.referrer;  // "http://somesite.com"

Get the previous page within a Wix site

This example demonstrates how to use session storage to know which page is the page a site visitor previously visited. The code below needs to be placed in the Site tab so that it runs on all your site's pages. The code retrieves the URL of the page a visitor previously visited from session storage. It then stores the URL of the vistor's current page in session storage. When the visitor navigates to another page, this stored URL is retrieved as the previous page URL.

// In Site tab

import {session} from 'wix-storage';
import wixLocation from 'wix-location';

let previousPageURL;

$w.onReady(function () {
  previousPageURL = session.getItem("page");
  session.setItem("page", wixLocation.url);
});

viewMode

Gets which mode the site is currently being viewed in.

Description

The viewMode property gets either:

  • "Preview": When previewing the site using the Preview button in the Editor.
  • "Site": When viewing the published site.

Syntax

get viewMode(): string
TYPE
?
The kind of data the property stores.
string

Examples

Get a window's view mode

import wixWindow from 'wix-window';

// ...

let viewMode = wixWindow.viewMode;  // "Site"

getBoundingRect( )

Returns information about the window.

Description

The getBoundingRect() function returns a Promise that resolves to an object containing information about the current window's size, the document's size, and the current scroll position.

Syntax

function getBoundingRect(): Promise<WindowSizeInfo>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Fulfilled - An object containing information about the window's size, the document's size, and the current scroll position.

Examples

Get information about the window

import wixWindow from 'wix-window';

// ...

wixWindow.getBoundingRect()
  .then( (windowSizeInfo) => {
    let windowHeight = windowSizeInfo.window.height;      // 565
    let windowWidth = windowSizeInfo.window.width;        // 1269
    let documentHeight = windowSizeInfo.document.height;  // 780
    let documentWidth = windowSizeInfo.document.width;    // 1269
    let scrollX = windowSizeInfo.scroll.x;                // 0
    let scrollY = windowSizeInfo.scroll.y;                // 120
  } );

getCurrentGeolocation( )

Returns the current geolocation of the user.

Description

The getCurrentGeolocation() function returns a Promise that resolves to an object containing the current geolocation of the user.

The object contains the following key:value pairs:

  • "timestamp": The geolocation timestamp representing the date and time at which the location was retrieved.
  • "coords": An object that defines the location.
    • "latitude": The position's latitude in decimal degrees.
    • "longitude": The position's longitude in decimal degrees.
    • "altitude": The position's altitude in metres, relative to sea level. This value may be null if the browser cannot provide the data.
    • "accuracy": The accuracy in meters of the latitude and longitude properties.
    • "altitudeAccuracy": The accuracy in meters of the altitude property. This value may be null.
    • "heading": The direction in degrees in which the device is traveling. It indicates how far off from heading true north the device is. If speed is 0, the heading is NaN. This value may be null if the browser cannot provide the data.
    • "speed": The velocity in meters per second of the device. This value may be null if the browser cannot provide the data.

Note

The getCurrentGeolocation() function has the following limitiations:

  • On Chrome, the function only works on HTTPS sites.
  • On Chrome, Firefox, and Safari, the function only works if the user approves a popup.

Syntax

function getCurrentGeolocation(): Promise<Object>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The coordinates and timestamp of the current location. Rejected - The user blocked the geolocation popup.

Examples

Get the geolocation data

import wixWindow from 'wix-window';

// ...

wixWindow.getCurrentGeolocation()
  .then( (obj) => {
    let timestamp = obj.timestamp;                  // 1495027186984
    let latitude = obj.coords.latitude;             // 32.0971036
    let longitude = obj.coords.longitude;           // 34.774391099999995
    let altitude = obj.coords.altitude;             // null
    let accuracy = obj.coords.accuracy;             // 29
    let altAccuracy = obj.coords.altitudeAccuracy;  // null
    let heading = obj.coords.heading;               // null
    let speed = obj.coords.speed;                   // null
  } )
  .catch( (error) => {
    let errorMsg = error;
  });

getRouterData( )

Returns the data that a router passed to the page in its response.

Description

When you create a router and define its functionality in its router() function, you can choose to send data along with the router's response. That data is retrieved in the code of the page that was routed to using the getRouterData() function.

If you call the getRouterData() function from a non-router page or a router page that wasn't sent any data, the function returns null.

See Also

router( ), WixRouterResponse

Syntax

function getRouterData(): Object
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Object
The data returned by the router.

Examples

Get the data passed by a router

import wixWindow from 'wix-window';

// ...

let routerData = wixWindow.getRouterData();

openLightbox( )

Opens a lightbox and optionally passes it the given data.

Description

The openLightbox() function returns a Promise which is resolved when the lightbox closes. If the lightbox is closed programmatically using its close() function, and the close() function was invoked with a data parameter, then the Promise resolves to that data object.

If you send a data object to the lightbox, use the getContext() function in the lightbox's code to access the received data.

To pass data to the lightbox that is opened, you must open the lightbox programmatically using the openLightbox() function. If the lightbox is opened automatically when the page loads or by a link from a page element, data will not be passed to the lightbox. Therefore, if you want to pass data to the lightbox, make sure Automatically display lightbox on pages is set to No in the Lightbox Settings panel in the Editor and don't set any element's link to open the lightbox. Instead, create your own method for opening the lightbox programmatically. For example, you can add a button with an onClick event handler that calls the openLightbox() function.

To pass data back to the page that opened the lightbox, you must close the lightbox programmatically using the close() function. If the lightbox is closed by the site visitor clicking the 'X' icon, close button, or lightbox overlay, data will not be passed back the the page that opened the lightbox. Therefore, if you want to make sure data is passed back to the page that opened the lightbox, disable all of the methods mentioned above and create your own method for closing the lightbox programmatically. For example, you can add a button with an onClick event handler that calls the close() function.

Note

Use the name of the lightbox and not the lightbox's ID when calling openLightbox().

See Also

openModal( )

Syntax

function openLightbox(name: string, [data: Object]): Promise<Object>
PARAMETERS
?
Values that you pass to a function.
name
string
The name of the lightbox to open.
data(Optional)
Object
The data to pass to the lightbox.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The returned data from the lightbox. Rejected - The error that caused the rejection.

Examples

Open a lightbox

import wixWindow from 'wix-window';

// ...

wixWindow.openLightbox("LightboxName");

Open a lightbox and send it data

import wixWindow from 'wix-window';

// ...

wixWindow.openLightbox("LightboxName", dataObj);

Open a lightbox and receive data when it is closed

import wixWindow from 'wix-window';

// ...

wixWindow.openLightbox("LightboxName")
  .then( (data) => {
    let receivedData = data;
  } );

Open a lightbox, send it data, and receive data back when it is closed

import wixWindow from 'wix-window';

// ...

wixWindow.openLightbox("LightboxName", dataObj)
  .then( (data) => {
    let receivedData = data;
  } );

A scenario where information is passed between a page and a lightbox

This example demonstrates how to pass data from a page to a lightbox that it opens and from the lightbox back to the page as it closes.

It assumes that the page has:

  • An open button that is used to open the lightbox.
  • Two text inputs where information that is to be passed to the lightbox is entered.
  • Two text elements where information that is passed from the lightbox is displayed.

It assumes that the lightbox has:

  • An close button that is used to close the lightbox.
  • Two text inputs where information that is to be passed to the page is entered.
  • Two text elements where information that is passed from the page is displayed.
/*************
 * Page Code *
 *************/

import wixWindow from 'wix-window';

export function openButton_click(event) {
  wixWindow.openLightbox("MyLightBox", {
    "pageSend1": $w('#pageSend1').value,
    "pageSend2": $w('#pageSend2').value
  })
  .then( (data) => {
    $w('#pageReceive1').text = data.lightboxSend1;
    $w('#pageReceive2').text = data.lightboxSend2;
  } );
}

/*****************
 * Lightbox Code *
 *****************/

import wixWindow from 'wix-window';

$w.onReady( function () {
  let received = wixWindow.lightbox.getContext();
  $w('#lightBoxReceive1').text = received.pageSend1;
  $w('#lightBoxReceive2').text = received.pageSend2;
} );

export function closeButton_click(event) {
  wixWindow.lightbox.close( {
    "lightBoxSend1": $w('#lightBoxSend1').value,
    "lightBoxSend2": $w('#lightBoxSend2').value
  } );
}

openModal( )

Opens a modal window that displays the specified web page.

Description

A modal window displays the page specified by the url property over your current page. Unlike a lightbox, which is open using the openLightbox() function, the window opened by openModal() is not part of your site structure.

Only one modal window can be open at any given time. Therefore, opening a modal window closes an already open modal window if there is one.

Note

The specified url must be an HTTPS URL. To use an HTTP URL, turn off SSL for your site.

See Also

openLightbox( )

Syntax

function openModal(url: string, options: OpenModalOptions): Promise<void>
PARAMETERS
?
Values that you pass to a function.
url
string
The URL of the page to show in the modal window.
options
The options used for the modal window.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When the modal window is closed. Rejected - The error that caused the rejection.

Examples

Open a modal window

import wixWindow from 'wix-window';

// ...

wixWindow.openModal("https://en.wikipedia.org/wiki/Wix.com", {
  "width": 750,
  "height": 500
} );

Open a modal window and log a message when it is closed

import wixWindow from 'wix-window';

// ...

wixWindow.openModal("https://en.wikipedia.org/wiki/Wix.com", {
    "width": 750,
    "height": 500
  } )
  .then( () => {
    console.log("Modal closed.");
  } );

postMessage( )

Sends a message to the page's parent.

Description

If a page is embedded within another site, using an HtmlComponent on a Wix site or an iframe on a non-Wix site, you can use the postMessage() function to send a message from the inner site to the outer site.

When the parent site is a Wix site, use the onMessage() function to receive the message on the parent page.

When the parent site is a non-Wix site, use the page's window.onmessage event handler to read the data property of the received MessageEvent to receive the message on the parent page.

Syntax

function postMessage(message: Object, [target: string]): Promise<Object>
PARAMETERS
?
Values that you pass to a function.
message
Object
The message to send.
target(Optional)
string
The target to send the message to. Must be "parent" or omitted. Defaults to "parent".
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The data returned from the modal window. Rejected - The error that caused the rejection.

Examples

Send a message to a Wix parent site

/* * * * * * * * * * * * * * * * * * * * * * *
 * Code for the inner site to post a message *
 * * * * * * * * * * * * * * * * * * * * * * */
import wixWindow from 'wix-window';

// ...

wixWindow.postMessage(dataObj);

/* * * * * * * * * * * * * * * * * * * * * * * * *
 * Code for the outer site to receive a message  *
 * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 * $w("#myHtmlComponent").onMessage( (event, $x) => {
 *   let message = event.data;
 * } );
 */

Send a message to a non-Wix parent site

/* * * * * * * * * * * * * * * * * * * * * * *
 * Code for the inner site to post a message *
 * * * * * * * * * * * * * * * * * * * * * * */
import wixWindow from 'wix-window';

// ...

wixWindow.postMessage(dataObj);

/* * * * * * * * * * * * * * * * * * * * * * * * *
 * Code for the outer site to receive a message  *
 * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 * <script>
 *   window.addEventListener("message", event => {
 *    let message = event.data;
 *   } );
 * </script>
 */

scrollBy( )

Scrolls the page by a given number of pixels.

Description

The scrollBy() function returns a Promise that resolves when the current page has been scrolled by the given number of pixels,

The x and y parameters determine the number of horizontal and vertical pixels to scroll the current page. Negative numbers scroll up or to the left and positive numbers scroll down or to the right.

Syntax

function scrollBy(x: number, y: number): Promise<void>
PARAMETERS
?
Values that you pass to a function.
x
number
The horizontal offset, in pixels, to scroll by.
y
number
The vertical offset, in pixels, to scroll by.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the scroll is complete.

Examples

Scroll the page by a given number of pixels

import wixWindow from 'wix-window';

// ...

wixWindow.scrollBy(100, 500);

Scroll the page by a given number of pixels and log message when done

import wixWindow from 'wix-window';

// ...

wixWindow.scrollBy(100, 500)
  .then( ( ) => {
    console.log("Done with scroll");
} );

scrollTo( )

Scrolls the page to a specific location.

Description

The scrollTo() function returns a Promise that resolves when the current page has been scrolled to the given location.

The x and y parameters determine the top-left pixel that is displayed on screen after the scroll.

To scroll to a specific element on the page, see the $w.Node scrollTo() function.

Syntax

function scrollTo(x: number, y: number): Promise<void>
PARAMETERS
?
Values that you pass to a function.
x
number
The horizontal position, in pixels, to scroll to.
y
number
The vertical position, in pixels, to scroll to.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the scroll is complete.

Examples

Scroll the page to a location

import wixWindow from 'wix-window';

// ...

wixWindow.scrollTo(100, 500);

Scroll the page to a location and log message when done

import wixWindow from 'wix-window';

// ...

wixWindow.scrollTo(100, 500)
  .then( ( ) => {
    console.log("Done with scroll");
} );

trackEvent( )

Sends a tracking event to external analytics tools.

Description

The trackEvent() function sends an event to analytics tools connected to your site. It can send events to Google Analytics and Facebook Pixel. To learn how to connect analytics tools to your site, see About Tracking Tools & Analytics.

The following events and parameters are available:

  • "AddProductImpression": parameters: When a user views a product. (Google Analytics only)
  • "ClickProduct": parameters: When a user clicks on a product. (Google Analytics only)
  • "ViewContent": parameters: When a key page is viewed.
  • "AddToCart": parameters: When a user adds a product to the shopping cart.
  • "RemoveFromCart": parameters: When a user removes a product from the shopping cart. (Google Analytics only)
  • "InitiateCheckout": parameters: When a user starts the checkout process.
  • "StartPayment": parameters: When a user starts the payment process. (Google Analytics only)
  • "AddPaymentInfo": parameters: When a user saves payment information.
  • "CheckoutStep": parameters: When a user completes a custom checkout step. (Google Analytics only)
  • "Purchase": parameters: When the checkout process is complete.
  • "Lead": When a user subscribes to a newsletter or submits a contact form.
  • "CustomEvent": parameters: When a user performs an event not listed above.

Note

The trackEvent() function only runs on published versions of your site. It does not work when previewing your site.

Syntax

function trackEvent(eventName: string, parameters: AddPaymentInfoEvent | AddProductImpressionEvent | AddToCartEvent | ClickProductEvent | CustomEvent | InitiateCheckoutEvent | PurchaseEvent | RemoveFromCartEvent | ViewContentEvent): void

Examples

Send a trackEvent with parameters

import wixWindow from 'wix-window';

wixWindow.trackEvent("ViewContent", {
  "origin": "My Sportswear Store",
  "id": "P12345",
  "name": "Really Fast Running Shoes",
  "category": "Apparel/Shoes",
  "price": 120,
  "currency": "USD",
  "brand": "SomeBrand",
  "variant": "Black",
  "position": 1
} );

Send a trackEvent that doesn't take any parameters

import wixWindow from 'wix-window';

wixWindow.trackEvent("Lead");

Send a trackEvent from the onReady event handler

import wixWindow from 'wix-window';

$w.onReady(function () {
  if(wixWindow.rendering.env === "browser") {
    wixWindow.trackEvent("ViewContent", {
      "origin": "My Sportswear Store",
      "id": "P12345",
      "name": "Really Fast Running Shoes",
      "category": "Apparel/Shoes",
      "price": 120,
      "currency": "USD",
      "brand": "SomeBrand",
      "variant": "Black",
      "position": 1
    } );
  }
} );

OpenModalOptions

An object used when opening a modal window.

See Also

openModal( )

Syntax

type OpenModalOptions = {
  width: number
  height: number
}
MEMBERS
?
The properties of an object.
width
number
Width of the modal window.
height
number
Height of the modal window.

Examples

Open a modal window

import wixWindow from 'wix-window';

// ...

wixWindow.openModal("https://en.wikipedia.org/wiki/Wix.com", {
  "width": 750,
  "height": 500
} );

WindowSizeInfo

An object returned by the getBoundingRect() function that contains information about the window's size, the document's size, and the current scroll position.

See Also

getBoundingRect( )

Syntax

type WindowSizeInfo = {
  window: Object
  document: Object
  scroll: Object
}
MEMBERS
?
The properties of an object.
window
Object
An object with height and width key:value pairs containing the size of the viewable area of the current browser window.
document
Object
An object with height and width key:value pairs containing the size of the actual body of the page, which may be larger or smaller than the current window.
scroll
Object
An object with x and y key:value pairs containing the scroll offset of the page within the window from the top-left corner.

Examples

Get information about the window

import wixWindow from 'wix-window';

// ...

wixWindow.getBoundingRect()
  .then( (windowSizeInfo) => {
    let windowHeight = windowSizeInfo.window.height;      // 565
    let windowWidth = windowSizeInfo.window.width;        // 1269
    let documentHeight = windowSizeInfo.document.height;  // 780
    let documentWidth = windowSizeInfo.document.width;    // 1269
    let scrollX = windowSizeInfo.scroll.x;                // 0
    let scrollY = windowSizeInfo.scroll.y;                // 120
  } );