# Unity Web 构建中的 JavaScript 接口

> Learn about some useful functions you can use in the JavaScript interface.

Unity Web 构建中的 JavaScript 接口提供了可用于配置 Web 应用程序的有用函数和变量。您可以在 JavaScript 库代码（.jslib 文件）中调用这些函数。

## 显示错误、警告或自定义横幅##display-error-warning-or-custom-banners

使用 `unityShowBanner()` 函数可显示消息横幅，或覆盖函数以根据您自己的目的自定义横幅。

| **参数** | **描述**                                                                           |
| ------ | -------------------------------------------------------------------------------- |
| `msg`  | 要显示的消息。                                                                          |
| `type` | 要显示的消息的类型。例如：使用 `type == error` 可在画布顶部显示永久错误消息。使用 `type == warning` 可在消息上突出显示黄色。 |

默认 WebGL 模板中的以下代码设置错误和警告横幅的外观。在自定义模板中，可以覆盖此函数来创建您自己的横幅类型，或自定义非关键警告和错误消息的显示方式。

```js
function unityShowBanner(msg, type) {
        var warningBanner = document.querySelector("#unity-warning");
        function updateBannerVisibility() {
          warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
        }
        var div = document.createElement('div');
        div.innerHTML = msg;
        warningBanner.appendChild(div);
        if (type == 'error') div.style = 'background: red; padding: 10px;';
        else {
          if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
          setTimeout(function() {
            warningBanner.removeChild(div);
            updateBannerVisibility();
          }, 5000);
        }
        updateBannerVisibility();
      }
```

您可以在 .jslib 文件中调用函数。以下横幅将**要显示的消息**永久显示为错误消息：

```js
unityShowBanner('The message you want to show', 'error');
```

## 更改 WebGL 上下文属性##change-webgl-context-attributes

使用 `webglContextAttributes` 可自定义用于初始化 WebGL 上下文的创建属性。只能更改以下属性：

* `powerPreference`
* `premultipliedAlpha`
* `preserveDrawingBuffer`

这些选项仅在使用 WebGL 渲染 API 时适用。如果使用 WebGPU 渲染 API，则会忽略 `webglContextAttributes` 字段。

要更改这些属性，请在自定义 WebGL 模板中更改配置对象。例如：

```js
script.onload = () => {
  config['webglContextAttributes'] = {

    powerPreference: 'high-performance',
    premultipliedAlpha: false,
    preserveDrawingBuffer: true, 
  };
  createUnityInstance(canvas, config, (progress) => {
```

`powerPreference` 属性具有以下选项：

| **选项**           | **描述**                     |
| ---------------- | -------------------------- |
| default          | 让用户代理决定哪种 GPU 配置最适合。这是默认值。 |
| high-performance | 使渲染性能优先于功耗。                |
| low-power        | 使节电优先于渲染性能。                |

有关每个属性的更多信息，请参阅有关 [HTMLCanvasElement: getContext()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext) 的 Mozilla 文档。

有关 Unity WebGL 图形的信息，请参阅 [WebGL 图形](/engine/6000.0/manual/platform-specific/webgl/develop/graphics.md)。

## 将项目定向到流媒体资源##direct-your-project-to-your-streaming-assets

如果需要在其他 CDN 上托管流媒体资源，可以调整 `createUnityInstance()` 配置对象上的 `streamingAssetsUrl` 属性以指向流媒体资源所在的完整 URL。

```js
var buildUrl = "Build";
var config = {
  dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}",
  frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}",
  codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",
#if MEMORY_FILENAME
  memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}",
#endif
#if SYMBOLS_FILENAME
  symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}",
#endif
   streamingAssetsUrl: "https://mygameserver.com/StreamingAssets/",  // Add this line to override the default streaming assets location
  companyName: "{{{ COMPANY_NAME }}}",
  productName: "{{{ PRODUCT_NAME }}}",
  productVersion: "{{{ PRODUCT_VERSION }}}",
};
```

## 控制网页缓存##control-cache-of-web-pages

使用 `cacheControl()` 函数可以控制在 `UnityCache` 中缓存哪些 URL。该函数接受 URL 作为参数，并返回 `must-revalidate`、`immutable` 或 `no-store`。您也可以根据自己的目的覆盖函数。

有关代码示例和更多信息，请参阅 [Web 中的缓存行为](/engine/6000.0/manual/platform-specific/webgl/develop/caching.md)。

## 其他资源##additional-resources

* [从 JavaScript 调用 Unity C# 脚本函数](/engine/6000.0/manual/platform-specific/webgl/develop/interactingwithbrowserscripting/web-interacting-browser-unity-to-js.md)
* [Web 图形](/engine/6000.0/manual/platform-specific/webgl/develop/graphics.md)
* [Web 中的缓存行为](/engine/6000.0/manual/platform-specific/webgl/develop/caching.md)
