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

# `<webview>`

APISummary
用于在 Lynx 中嵌入网页，提供灵活的方式集成现有 Web 资源并加速开发。

- `<webview>` 在元素侧作为视口，必须有确定的宽度。
- `<webview>` 在元素侧作为视口，必须有确定的高度。
- Web 资源渲染完成后，可使用 `document.getElementById` 获取自身高度，通过 message 通知 `<webview>` 修改高度。
- 除非在 `<webview />` 上设置 `native-interaction-enabled={false}`，否则 `<webview>` 的交互事件无法穿透到其他元素。
- `<webview>` 不能与其他可滚动元素嵌套使用，如有需要请使用 `<scroll-view>` 进行包裹。
- 若需拦截点击事件，需在 `<webview />` 上手动添加 `catchtap={() => {}}`。

## 使用指南

### 加载 Web 内容


**下面是一个示例: 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



### 加载 HTML 字符串


**下面是一个示例: 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



## 属性

### `bounces`

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

启用弹性效果

### `cookies`

Desktop
Lynx 3.5

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

预设 cookies

### `enable-debug`

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

启用 WebView 调试，可在 Chrome DevTools 中进行调试

### `html`

Android
iOS
Harmony
3.6

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

表示要加载的 HTML 内容的字符串。当 html 变化时会自动触发内容刷新。优先级低于 `src`。

### `initjs`

Desktop
Lynx 3.5

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

在文档就绪时执行的 JavaScript

### `params`

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

外部 webview 实现的参数

### `scroll-bar-enable`

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

启用滚动条

### `src`

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

表示远程服务器上资源位置的字符串。当 src 变化时会自动触发内容刷新。

### `use-osr`

Desktop
Lynx 3.5

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

是否启用离屏渲染模式

### `webview-type`

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

指定 webview 的类型，可以是通过 LynxService 注入的 webview 实现

## 事件

前端可以绑定对应的事件回调来监听元素的运行时行为，如下所示。

### `binderror`

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

| 字段        | 类型     | 可选 | 默认值 | 平台                                                       | 起始版本 | 描述         |
| --------- | ------ | -- | --- | -------------------------------------------------------- | ---- | ---------- |
| errorCode | number | 否  | –   | <AndroidOnly /> <IOSOnly /> <ClayOnly /> <HarmonyOnly /> |      | 表示错误码的数字   |
| errorMsg  | string | 否  | –   | <AndroidOnly /> <IOSOnly /> <ClayOnly /> <HarmonyOnly /> |      | 表示错误信息的字符串 |

加载错误事件

### `bindload`

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

加载成功事件

### `bindlocationchange`

Desktop
Lynx 3.5

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

| 字段  | 类型     | 可选 | 默认值 | 平台           | 起始版本 | 描述            |
| --- | ------ | -- | --- | ------------ | ---- | ------------- |
| url | string | 否  | –   | <ClayOnly /> |      | 表示目标 URL 的字符串 |

页面地址变化事件

### `bindmessage`

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

| 字段  | 类型     | 可选 | 默认值 | 平台                                                       | 起始版本 | 描述         |
| --- | ------ | -- | --- | -------------------------------------------------------- | ---- | ---------- |
| msg | string | 否  | –   | <AndroidOnly /> <IOSOnly /> <ClayOnly /> <HarmonyOnly /> |      | 表示消息内容的字符串 |

来自 JavaScript 的消息事件

### `bindopenwindow`

Desktop
Lynx 3.5

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

| 字段  | 类型     | 可选 | 默认值 | 平台           | 起始版本 | 描述            |
| --- | ------ | -- | --- | ------------ | ---- | ------------- |
| url | string | 否  | –   | <ClayOnly /> |      | 表示目标 URL 的字符串 |

打开新窗口事件

## 方法

前端可以通过 [SelectorQuery](/next/zh/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();

```

将所有未写入的 cookies 数据刷新到磁盘

### `cookies.get`

Desktop
Lynx 3.5

```ts
interface CookiesGetParams {
  /**
   * 获取域名匹配或为其子域名的 cookies
   * @PC
   */
  domain?: string;
  /**
   * 按 httpOnly 过滤 cookies
   * @PC
   */
  httpOnly?: boolean;
  /**
   * 按名称过滤 cookies
   * @PC
   */
  name?: string;
  /**
   * 获取路径匹配的 cookies
   * @PC
   */
  path?: string;
  /**
   * 按 Secure 属性过滤 cookies
   * @PC
   */
  secure?: boolean;
  /**
   * 过滤会话 cookie 或持久化 cookie
   * @PC
   */
  session?: boolean;
  /**
   * 获取与指定 URL 关联的 cookies。为空则获取所有 URL 的 cookies
   * @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();

```

从 webview 获取 cookies

### `cookies.remove`

Desktop
Lynx 3.5

```ts
interface CookiesRemoveParams {
  /**
   * 要删除的 cookie 名称
   * @PC
   */
  name?: string;
  /**
   * 与 cookie 关联的 URL
   * @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();

```

删除匹配 url 和 name 的 cookies

### `cookies.set`

Desktop
Lynx 3.5

```ts
interface CookiesSetParams {
  /**
   * cookie 的域名。省略时默认为空
   * @PC
   */
  domain?: string;
  /**
   * cookie 的过期时间，为 UNIX 纪元以来的秒数
   * @PC
   */
  expirationDate?: number;
  /**
   * cookie 是否标记为 HTTP only
   * @PC
   * @defaultValue false
   */
  httpOnly?: boolean;
  /**
   * cookie 的名称
   * @PC
   */
  name: string;
  /**
   * cookie 的路径。省略时默认为空
   * @PC
   */
  path?: string;
  /**
   * 应用于此 cookie 的 Same Site 策略。可为 unspecified、no_restriction、lax 或 strict
   * @PC
   * @defaultValue 'lax'
   */
  sameSite?: string;
  /**
   * cookie 是否标记为 secure
   * @PC
   * @defaultValue false
   */
  secure?: boolean;
  /**
   * 关联 cookie 的 URL
   * @PC
   */
  url: string;
  /**
   * cookie 的值。省略时默认为空
   * @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();

```

为 webview 设置 cookie

### `eval`

Android
iOS
Desktop
Harmony
```ts

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

```

调用 JavaScript 函数

### `reload`

Android
iOS
Desktop
Harmony
```ts

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

```

重新加载 webview

## 兼容性


**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

