# 背景服務

背景服务插件与[窗口插件](https://developer.eagle.cool/plugin-api/zh-cn/get-started/plugin-types/window)开发方式类似，主要区别在于代码的执行时机。背景服务插件会在软件启动时自动启动，而窗口插件只会在用户点击时执行。要创建一个背景服务插件，只需要在 `manifest.json` 中的 `main` 字段添加 `"serviceMode": true`，如下所示：

```json
{
    "main":
    {
        "serviceMode": true,    // 主要差异
        "url": "index.html",
        "width": 640,
        "height": 480
    }
}
```

背景服务插件也能弹出窗口，你可以在这个窗口显示当前背景任务的进度、状态，以便用户可以清楚地了解插件的当前状态。

最终代码如下：

{% tabs %}
{% tab title="manifest.json" %}

```json
{
    "id": "LBCZEHP8BBO94",
    "version": "1.0.0",
    "name": "Service Plugin",
    "logo": "/logo.png",
    "keywords": [],
    "main":
    {
        "serviceMode": true,
        "url": "index.html",
        "width": 640,
        "height": 480
    }
}
```

{% endtab %}

{% tab title="index.html" %}

```html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <script type="text/javascript" src="js/plugin.js"></script>
</head>

<body>
    <div>Background services can be without UI, but you can still display the status of background services here.</div>
</body>
</html>
```

{% endtab %}

{% tab title="plugin.js" %}

```javascript
console.log(`Plugins will be created automatically, no need for users to execute them.`);

eagle.onPluginCreate((plugin) => {
    console.log('eagle.onPluginCreate');
    console.log(plugin);
});

eagle.onPluginShow(() => {
    console.log('eagle.onPluginShow');
});

eagle.onPluginHide(() => {
    console.log('eagle.onPluginHide');
});
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**完整示例代码：**

<https://github.com/eagle-app/eagle-plugin-examples/tree/main/Service>
{% endhint %}

{% hint style="info" %}
注：你可以查看这篇文章，[了解 `manifest.json`的所有配置方式](https://developer.eagle.cool/plugin-api/zh-cn/tutorial/manifest)。
{% endhint %}

{% hint style="warning" %}
**注意：** 如果插件执行过程必须依赖相对的资源库路径，你可能需要透过[`onLibraryChanged(callback)`](https://developer.eagle.cool/plugin-api/zh-cn/api/event#g3tny)，在资源库切换时，做出对应的调整，避免程序执行过程发生错误。
{% endhint %}
