> For AI agents: the complete documentation index is available at /next/llms.txt, the full documentation bundle is available at /next/llms-full.txt.

# `<webview>`

APISummary
Used to embed web pages in Lynx, providing a flexible way to integrate existing web resources and accelerate development.

- `<webview>` acts as a viewport on the element side and must have a fixed width.
- `<webview>` acts as a viewport on the element side and requires a fixed height.
- After the web resource finishes rendering, use `document.getElementById` to obtain its height, then notify `<webview>` to adjust the height via message.
- Unless `native-interaction-enabled={false}` is set on `<webview />`, interaction events of `<webview>` cannot pass through to other elements.
- `<webview>` cannot be nested with other scrollable elements; if needed, wrap it with `<scroll-view>`.
- To intercept click events, manually add `catchtap={() => {}}` to `<webview />`.

## Usage

### Load Web Content


**This is an example below: webview**

**Bundle:** `dist/base.lynx.bundle`

```tsx
// Copyright 2024 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.

import { root, useRef, useState } from "@lynx-js/react";

import "./index.scss";

function App() {
  const webviewRef = useRef<any>(undefined);
  const [url, setUrl] = useState<string>("https://www.github.com");

  return (
    <view style="width:100vw;height:100vh">
      <view style="width:100%;height:100px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);display:flex;flex-direction:column;align-items:center;justify-content:center;box-shadow:0 6px 12px rgba(0,0,0,0.15);">
        <text style="color:#ffffff;font-size:28px;font-weight:bold;letter-spacing:3px;text-shadow:0 2px 4px rgba(0,0,0,0.2);">
          WebView Demo
        </text>
        <text style="background:rgba(255,255,255,0.25);padding:6px 20px;border-radius:20px;font-size:14px;color:#ffffff;margin-top:8px;">
          Powered by Lynx
        </text>
      </view>
      <view style="width:100%;padding:16px;display:flex;justify-content:center;">
        <view
          style="background:linear-gradient(135deg, #f093fb 0%, #f5576c 100%);padding:12px 32px;border-radius:25px;box-shadow:0 4px 15px rgba(245,87,108,0.4);"
          bindtap={() => {
            setUrl("https://www.google.com");
          }}
        >
          <text style="color:#ffffff;font-size:16px;font-weight:600;letter-spacing:1px;">
            🔄 Switch to Google
          </text>
        </view>
      </view>

      <webview
        style={"width: 100vw; height: 100%"}
        ref={webviewRef}
        src={url}
        bindload={() => {
          const jsCode = `
            const javascriptFunc = (arg) => {
                console.log("execute");
                if (window) {
                    window.postMessage("Hello from JavaScript " + arg);
                }
            };
            javascriptFunc('good');
          `;
          webviewRef?.current
            ?.invoke({
              method: "eval",
              params: {
                func: jsCode,
              },
            })
            .exec();
        }}
        bindmessage={(e: any) => {
          console.log("message: ", e.detail.msg);
        }}
      />
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.2.0



### Load HTML String


**This is an example below: webview**

**Bundle:** `dist/base.lynx.bundle`

```tsx
// Copyright 2024 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.

import { root, useRef, useState } from "@lynx-js/react";

import "./index.scss";

const defaultHtml = `<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Lynx WebView HTML Demo</title>
</head>
<body style="margin:0;padding:16px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;line-height:1.6;">
  <div style="max-width:720px;margin:0 auto;">
    <h1 style="font-size:20px;margin:0 0 8px;">Hello from HTML prop</h1>
    <p style="margin:0 0 8px;font-size:14px;">This content is loaded via the <code>html</code> prop.</p>
    <div style="display:flex;gap:8px;align-items:center;margin-top:12px;">
      <button id="btn" style="padding:6px 10px;border:1px solid #ddd;border-radius:6px;background:#f5f5f5;color:#111;font-size:14px;cursor:pointer;">Click Me</button>
      <span id="status" style="font-size:13px;color:#666;">Status: idle</span>
    </div>
  </div>
  <script>
    (function(){
      var btn = document.getElementById('btn');
      var status = document.getElementById('status');
      if (btn) {
        btn.addEventListener('click', function(){
          status.textContent = 'Status: clicked @ ' + new Date().toLocaleTimeString();
        });
      }
    })();
  </script>
</body>
</html>`;

const updatedHtml = `<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Lynx WebView HTML Demo</title>
</head>
<body style="margin:0;padding:16px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;line-height:1.6;">
  <div style="max-width:720px;margin:0 auto;">
    <h1 style="font-size:20px;margin:0 0 8px;">Updated HTML Content</h1>
    <p style="margin:0 0 8px;font-size:14px;">The <code></scrip>html</code> prop has been updated successfully.</p>
    <div style="display:flex;gap:8px;align-items:center;margin-top:12px;">
      <button id="btn" style="padding:6px 10px;border:1px solid #ddd;border-radius:6px;background:#e0f7fa;color:#00695c;font-size:14px;cursor:pointer;">Click Me</button>
      <span id="status" style="font-size:13px;color:#666;">Status: idle</span>
    </div>
  </div>
  <script>
    (function(){
      var btn = document.getElementById('btn');
      var status = document.getElementById('status');
      if (btn) {
        btn.addEventListener('click', function(){
          status.textContent = 'Status: clicked @ ' + new Date().toLocaleTimeString();
        });
      }
    })();
  </script>
</body>
</html>`;

function App() {
  const webviewRef = useRef<any>(undefined);
  const [html, setHtml] = useState<string>(defaultHtml);

  return (
    <view style="width:100vw;height:100vh">
      <view style="width:100%;height:100px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);display:flex;flex-direction:column;align-items:center;justify-content:center;box-shadow:0 6px 12px rgba(0,0,0,0.15);">
        <text style="color:#ffffff;font-size:28px;font-weight:bold;letter-spacing:3px;text-shadow:0 2px 4px rgba(0,0,0,0.2);">
          WebView HTML Demo
        </text>
        <text style="background:rgba(255,255,255,0.25);padding:6px 20px;border-radius:20px;font-size:14px;color:#ffffff;margin-top:8px;">
          Powered by Lynx
        </text>
      </view>
      <view style="width:100%;padding:16px;display:flex;justify-content:center;">
        <view
          style="background:linear-gradient(135deg, #f093fb 0%, #f5576c 100%);padding:12px 32px;border-radius:25px;box-shadow:0 4px 15px rgba(245,87,108,0.4);"
          bindtap={() => {
            setHtml(updatedHtml);
          }}
        >
          <text style="color:#ffffff;font-size:16px;font-weight:600;letter-spacing:1px;">
            🔄 Update HTML
          </text>
        </view>
      </view>

      <webview
        style={"width: 100vw; height: 100%"}
        ref={webviewRef}
        html={html}
        bindload={() => {
          const jsCode = `
            const javascriptFunc = (arg) => {
                console.log("execute");
                if (window) {
                    window.postMessage("Hello from JavaScript " + arg);
                }
            };
            javascriptFunc('good');
          `;
          webviewRef?.current
            ?.invoke({
              method: "eval",
              params: {
                func: jsCode,
              },
            })
            .exec();
        }}
        bindmessage={(e: any) => {
          console.log("message: ", e.detail.msg);
        }}
      />
    </view>
  );
}

root.render(<App />);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.2.0



## Attributes

### `bounces`

iOS
```tsx
// @defaultValue: false
bounces?: boolean;
```

Enable bounce effect

### `cookies`

Desktop
Lynx 3.5

```tsx
cookies?: any;
```

Preset cookies

### `enable-debug`

Android
iOS
Desktop
Harmony
```tsx
// @defaultValue: false
'enable-debug'?: boolean;
```

Enable WebView debugging in Android so that it can be debugged in Chrome DevTools

### `html`

Android
iOS
Harmony
3.6

```tsx
html?: string;
```

A string that represents the html content to load. Automatically trigger content refresh when the html changes. Priority lower than
`src`
.

### `initjs`

Desktop
Lynx 3.5

```tsx
initjs?: string;
```

Execute javascript when document ready

### `params`

Android
iOS
```tsx
params?: object;
```

Params for external webview implementation

### `scroll-bar-enable`

iOS
```tsx
// @defaultValue: false
'scroll-bar-enable'?: boolean;
```

Enable scrollbar

### `src`

Android
iOS
Desktop
Harmony
```tsx
src?: string;
```

A string that represents the location of a resource on a remote server. Automatically trigger content refresh when the src changes

### `use-osr`

Desktop
Lynx 3.5

```tsx
// @defaultValue: false
'use-osr'?: boolean;
```

Whether enable offscreen rendering mode

### `webview-type`

Android
iOS
Harmony
```tsx
// @defaultValue: 'default'
'webview-type'?: string;
```

Specify the type of webview, it could be a implementation of a webview inject from LynxService

## Events

Frontend can bind corresponding event callbacks to listen for runtime behaviors of the element, as shown below.

### `binderror`

Android
iOS
Desktop
Harmony
```tsx
binderror = (e: WebviewErrorEvent) => {};
```

| Field     | Type   | Optional | Default | Platforms                                                | Since | Description                                |
| --------- | ------ | -------- | ------- | -------------------------------------------------------- | ----- | ------------------------------------------ |
| errorCode | number | No       | –       | <AndroidOnly /> <IOSOnly /> <ClayOnly /> <HarmonyOnly /> |       | A number that represents the error code    |
| errorMsg  | string | No       | –       | <AndroidOnly /> <IOSOnly /> <ClayOnly /> <HarmonyOnly /> |       | A string that represents the error message |

Error event

### `bindload`

Android
iOS
Desktop
Harmony
```tsx
bindload = (e: BaseEvent) => {};
```

Load success event

### `bindlocationchange`

Desktop
Lynx 3.5

```tsx
bindlocationchange = (e: WebviewUrlEvent) => {};
```

| Field | Type   | Optional | Default | Platforms    | Since | Description                             |
| ----- | ------ | -------- | ------- | ------------ | ----- | --------------------------------------- |
| url   | string | No       | –       | <ClayOnly /> |       | A string that represents the target url |

location change event

### `bindmessage`

Android
iOS
Desktop
Harmony
```tsx
bindmessage = (e: WebviewMessageEvent) => {};
```

| Field | Type   | Optional | Default | Platforms                                                | Since | Description                          |
| ----- | ------ | -------- | ------- | -------------------------------------------------------- | ----- | ------------------------------------ |
| msg   | string | No       | –       | <AndroidOnly /> <IOSOnly /> <ClayOnly /> <HarmonyOnly /> |       | A string that represents the message |

Message post from javascript

### `bindopenwindow`

Desktop
Lynx 3.5

```tsx
bindopenwindow = (e: WebviewUrlEvent) => {};
```

| Field | Type   | Optional | Default | Platforms    | Since | Description                             |
| ----- | ------ | -------- | ------- | ------------ | ----- | --------------------------------------- |
| url   | string | No       | –       | <ClayOnly /> |       | A string that represents the target url |

open window event

## Methods

Frontend can invoke component methods via the [SelectorQuery](/next/api/lynx-api/nodes-ref/nodes-ref-invoke.md) API.

### `cookies.flushStore`

Desktop
Lynx 3.5

```ts

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'cookies.flushStore',
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

Write any unwritten cookies data to disk for webview

### `cookies.get`

Desktop
Lynx 3.5

```ts
interface CookiesGetParams {
  /**
   * Retrieves cookies whose domains match or are subdomains of domains
   * @PC
   */
  domain?: string;
  /**
   * Filters cookies by httpOnly
   * @PC
   */
  httpOnly?: boolean;
  /**
   * Filters cookies by name
   * @PC
   */
  name?: string;
  /**
   * Retrieves cookies whose path matches path
   * @PC
   */
  path?: string;
  /**
   * Filters cookies by their Secure property
   * @PC
   */
  secure?: boolean;
  /**
   * Filters out session or persistent cookies
   * @PC
   */
  session?: boolean;
  /**
   * Retrieves cookies which are associated with url. Empty implies retrieving cookies of all URLs
   * @PC
   */
  url?: string;
}

const params: CookiesGetParams = { domain: 'example.com', httpOnly: true, name: 'session', path: '/', secure: true, session: false, url: 'https://example.com' };

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'cookies.get',
      params,
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

Get cookies from webview

### `cookies.remove`

Desktop
Lynx 3.5

```ts
interface CookiesRemoveParams {
  /**
   * The name of cookie to remove.
   * @PC
   */
  name?: string;
  /**
   * The URL associated with the cookie.
   * @PC
   */
  url: string;
}

const params: CookiesRemoveParams = { name: 'session', url: 'https://example.com' };

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'cookies.remove',
      params,
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

Removes the cookies matching url and name

### `cookies.set`

Desktop
Lynx 3.5

```ts
interface CookiesSetParams {
  /**
   * The domain of the cookie. Empty by default if omitted
   * @PC
   */
  domain?: string;
  /**
   * The expiration date of the cookie as the number of seconds since the UNIX epoch
   * @PC
   */
  expirationDate?: number;
  /**
   * Whether the cookie should be marked as HTTP only
   * @PC
   * @defaultValue false
   */
  httpOnly?: boolean;
  /**
   * The name of the cookie
   * @PC
   */
  name: string;
  /**
   * The path of the cookie. Empty by default if omitted
   * @PC
   */
  path?: string;
  /**
   * The Same Site policy to apply to this cookie. Can be unspecified, no_restriction, lax or strict
   * @PC
   * @defaultValue 'lax'
   */
  sameSite?: string;
  /**
   * Whether the cookie should be marked as secure
   * @PC
   * @defaultValue false
   */
  secure?: boolean;
  /**
   * The URL to associate the cookie with
   * @PC
   */
  url: string;
  /**
   * The value of the cookie. Empty by default if omitted
   * @PC
   */
  value?: string;
}

const params: CookiesSetParams = { domain: 'example.com', expirationDate: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 30, httpOnly: true, name: 'session', path: '/', sameSite: 'lax', secure: true, url: 'https://example.com', value: 'hello' };

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'cookies.set',
      params,
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

Set a cookie to webview

### `eval`

Android
iOS
Desktop
Harmony
```ts

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'eval',
      params: {
        /**
         * Name of the function: `javascriptFunc(arg1, arg2)`.
         * @Android
         * @iOS
         * @Harmony
         * @PC
         */
        func: 'javascriptFunc(1, 2)',
      },
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

Call js function

### `reload`

Android
iOS
Desktop
Harmony
```ts

lynx.createSelectorQuery()
     .select('#id')
     .invoke({
      method: 'reload',
      success: function (res) {},
      fail: function (res) {},
    })
    .exec();

```

Reload the webview

## Compatibility


**Compatibility Table**
**Query:** `elements.webview`

**Platform Support**

| Platform | Version Added | Notes |
|----------|---------------|-------|
| Android | 4.0 | - |
| iOS | 4.0 | - |
| HarmonyOS | 4.0 | - |
| Clay Android | 4.0 | - |
| Clay iOS | 4.0 | - |
| Clay Windows | 4.0 | - |
| Clay macOS | 4.0 | - |
| Web | ✅ Yes | Mapped to <code>x-webview</code>. Only the Web attributes, events, and methods listed below are supported.; ⚠️ Partial implementation |

**Description:** webview

