> For the complete documentation index, see [llms.txt](https://docs.gpmautomate.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gpmautomate.com/automate-zh/cao-zuo-zhi-nan/javascript/execute-javascript-code.md).

# 执行JS代码

执行 JS 代码是一项极其强大的操作，允许您通过直接在当前网页上运行 JavaScript (JS) 代码片段来深入干预浏览器。此操作帮助您处理复杂的逻辑算法、数学计算、高级数据提取或执行常规无代码块不支持的交互操作。

#### 配置参数：

* JS 文件或代码的路径：您可以在此框中直接编写/粘贴 JavaScript 代码，或输入一个绝对路径到您计算机上存储的 `.js` 文件。
* 输出变量：GPM Automate 的变量名称，用于接收代码执行完毕后返回的值。

#### ⚠️ 编写 GPM Automate 中 JS 代码时的核心注意事项：

1. 必须有 `return` 语句：为了让 GPM Automate 系统能够接收代码处理的结果并存储到输出变量中，您必须在 JS 代码的末尾添加 `return` 语句。如果没有 `return`，输出变量将接收空值 (`undefined`)。如果您的 JS 代码不需要返回任何值，则不需要 `return` 语句。
2. 此操作 **必须** 放在主逻辑块中，它类似于您在浏览器的开发工具中运行 JS 代码。您可以在使用它在 Automate 中之前先在开发工具中测试您的 JS 代码。
3. 将 Automate 变量嵌入 JS 的规则：您可以通过语法 `$变量名` 在 JS 代码块中调用之前保存的 GPM Automate 变量。
   * 对于数字类型的变量 (Number)：您可以直接写入（例如：`const index = $index;`）。
   * 对于字符串类型的变量 (String)：您必须用单引号 `'...'`、双引号 `"..."`，或最标准的反引号 `` `...` `` 将该变量包裹起来，以避免在字符串中有空格或特殊字符时代码格式破损，例如：``const str = `$postContent`;``。

#### 实际示例：根据指定位置 (Index) 提取字符

假设在 GPM Automate 的脚本中，您已经有了 2 个变量：

* 变量 `$str` 存储字符串：`Hello, world!`
* 变量 `$index` 存储数字：`7`

您想使用 JavaScript 代码提取上述字符串中第 7 个位置的字符（期望结果是字母 `w`），并将其存储到 Automate 的变量 `$charResult` 中。您将配置执行 JS 代码的操作如下：

* 输出变量：`charResult`
* JS 代码内容：

```
const str = `$str`;
const index = $index;
const char = index >= 0 && index < str.length ? str[index] : "无效索引";

return char;
```

逻辑运作：系统将字符串 `Hello, world!` 和数字 `7` 加载到代码中，运行验证位置有效性的算法并提取字符。末尾的 `return char;` 将字母 `w` 推送到外部并直接加载到变量 `$charResult` 中，以便您在后续操作中使用。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.gpmautomate.com/automate-zh/cao-zuo-zhi-nan/javascript/execute-javascript-code.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
