这是原厂英文文档的翻译页面. 欢迎帮助我们 完善文档.

19 Browser监控项

Overview

Browser items allow monitoring complex websites and web applications using a browser.

The support of Browser items is currently experimental.

Browser items collect data by executing a user-defined JavaScript code and retrieving data over HTTP/HTTPS. This item can simulate such browser-related actions as clicking, entering text, navigating through web pages, and other user interactions with websites or web applications.

In addition to the script, an optional list of parameters (pairs of name and value) and timeout can be specified.

The item partially implements the W3C WebDriver standard with either Selenium Server or a plain WebDriver (for example, ChromeDriver) as a web testing endpoint. For the item to work, set the endpoint in the Zabbix server/proxy configuration file WebDriverURL parameter.

Browser items are executed and processed by Zabbix server or proxy browser pollers. If necessary, you can adjust the number of pre-forked instances of Browser item pollers in the Zabbix server/proxy configuration file StartBrowserPollers parameter.

For monitoring complex websites and web applications, the Website by Browser template is available as an out-of-the-box template.

配置

如果使用 ChromeDriver 作为网络测试端点,请参阅 安全注意事项

监控项配置表类型 字段中,选择 Browser,然后填写必填字段。

所有标红星号为必填字段。

Browser 监控项需要特定信息的字段有:

字段 描述
Key 输入用于识别监控项的唯一密钥。
**参数* 指定作为属性和值对传递给脚本的变量。
支持用户宏。要查看支持哪些内置宏,可以在支持的宏表中搜索 "Browser-type item"。
脚本 在点击参数字段(或旁边的查看/编辑按钮)时出现的代码块中输入 JavaScript 代码。此代码必须提供返回度量值的逻辑。
代码可以访问所有参数,以及 Zabbix 添加的所有额外的JavaScript 对象Browser监控项JavaScript对象
See also: JavaScript Guide.
超时 JavaScript 执行超时(1-600 秒;超出此时间将返回错误)。
请注意,根据脚本的不同,超时可能需要更长的时间才能触发。
有关超时参数的更多信息,请参见 通用监控项属性

示例

默认脚本

以下脚本:

  1. 初始化一个浏览器会话。
  2. 导航到指定的 URL。
  3. 收集性能条目和会话统计数据,并以 JSON 字符串的形式返回它们。

脚本字段中,输入以下内容:

var browser = new Browser(Browser.chromeOptions());
       
       try {
           browser.navigate("http://example.com");
           browser.collectPerfEntries();
       }
       finally {
           return JSON.stringify(browser.getResult());
       }
检查 Zabbix 登录

脚本执行以下操作:

  1. 初始化一个浏览器会话。
  2. 导航到 Zabbix 登录页面。
  3. 输入用户名 "Admin" 和密码 "zabbix"。
  4. 查找并点击登录按钮。
  5. 查找并点击注销按钮。
  6. 收集登录前后以及注销后的性能数据。
  7. 通过捕获错误消息和屏幕截图来处理错误。
  8. 将收集到的结果作为 JSON 字符串返回。

脚本 字段中,输入以下 JavaScript 代码:

var browser, result;
       
       browser = new Browser(Browser.chromeOptions());
       
       try {
           browser.navigate("http://example.com/zabbix/index.php");
           browser.collectPerfEntries("open page");
       
           var el = browser.findElement("xpath", "//input[@id='name']");
           if (el === null) {
               throw Error("cannot find name input field");
           }
           el.sendKeys("Admin");
       
           el = browser.findElement("xpath", "//input[@id='password']");
           if (el === null) {
               throw Error("cannot find password input field");
           }
           el.sendKeys("zabbix");
       
           el = browser.findElement("xpath", "//button[@id='enter']");
           if (el === null) {
               throw Error("cannot find login button");
           }
           el.click();
       
           browser.collectPerfEntries("login");
       
           el = browser.findElement("link text", "Sign out");
           if (el === null) {
               throw Error("cannot find logout button");
           }
           el.click();
       
           browser.collectPerfEntries("logout");
       
           result = browser.getResult();
       }
       catch (err) {
           if (!(err instanceof BrowserError)) {
               browser.setError(err.message);
           }
           result = browser.getResult();
           result.error.screenshot = browser.getScreenshot();
       }
       finally {
           return JSON.stringify(result);
       }

The following script:

  1. Initializes a browser session.
  2. Defines a function for removing duplicate elements from an array (see step 5).
  3. Navigates to a page (specified as parameters, see below).
  4. Finds links on the page.
  5. Removes duplicate links to ensure they are unique.
  6. Extracts only the links that start with "http".
  7. Formats the extracted links to a specific structure.
  8. Handles errors by capturing error messages and a screenshot.
  9. Returns the collected results as a JSON string.

The script also uses parameters from the item configuration form:

  • scheme - {$WEBSITE.SCHEME}
  • domain - {$WEBSITE.DOMAIN}
  • path - {$WEBSITE.PATH}

In the Script field, enter:

var browser, result;
       
       browser = new Browser(Browser.chromeOptions());
       
       try {
           var params = JSON.parse(value);  // Parse the JSON string containing parameters passed from Zabbix.
       
           function uniq(a) {
               return a.sort().filter(function (item, pos, ary) {
                   return !pos || item != ary[pos - 1];
               });
           }
       
           browser.navigate(params.scheme + '://' + params.domain + params.path);
       
           var el = browser.findElements("link text", "");
           var links = [];
           for (var n = 0; n < el.length; n++) {
               links.push(el[n].getAttribute('href'));
           }
       
           links = uniq(links);
       
           result = [];
           for (i = 0; i < links.length; i++) {
               if (links[i].match(/^http.*/)) {
                   var row = {};
                   row["{#URL}"] = links[i];
                   result.push(row);
               }
           }
       }
       catch (err) {
           if (!(err instanceof BrowserError)) {
               browser.setError(err.message);
           }
           result = browser.getResult();
           result.error.screenshot = browser.getScreenshot();
       }
       finally {
           return JSON.stringify(result);
       }
初始化浏览器

以下脚本执行以下操作:

  1. 根据脚本中指定的顺序,为可用的浏览器初始化一个浏览器会话,选择第一个匹配的浏览器。
  2. 定义浏览器能力,包括页面加载策略以及针对每个浏览器的特定选项,例如 Chrome、Firefox 和 Microsoft Edge 浏览器的无头模式。

请注意,为了设置 WebDriver 实例,您将需要额外的测试脚本或场景来与被测试的网站或 Web 应用程序进行交互。

脚本字段中,输入以下内容:

var browser = new Browser({
           "capabilities":{
               "firstMatch":[
                   {
                       "browserName":"chrome",
                       "pageLoadStrategy":"normal",
                       "goog:chromeOptions":{
                           "args":[
                               "--headless=new"
                           ]
                       }
                   },
                   {
                       "browserName":"firefox",
                       "pageLoadStrategy":"normal",
                       "moz:firefoxOptions":{
                           "args":[
                               "--headless"
                           ]
                       }
                   },
                   {
                       "browserName":"MicrosoftEdge",
                       "pageLoadStrategy":"normal",
                       "ms:edgeOptions":{
                           "args":[
                               "--headless=new"
                           ]
                       }
                   },
                   {
                       "browserName":"safari",
                       "pageLoadStrategy":"normal"
                   }
               ]
           }
       });
Initialize browser with GUI

By default, browser sessions (excluding Safari) are initialized in headless mode, meaning the browser's graphical user interface (GUI) is not displayed.

The following script initializes a browser session with the GUI enabled.

Note that if the WebDriver cannot locate the browser binary, you can specify the path manually.

var opts = Browser.chromeOptions();
       opts.capabilities.alwaysMatch['goog:chromeOptions'].args = [];
       
       // To initialize a Firefox session with GUI, uncomment the following lines:
       // var opts = Browser.firefoxOptions();
       // opts.capabilities.alwaysMatch['moz:firefoxOptions'].binary = 'usr/bin/firefox';
       // opts.capabilities.alwaysMatch['moz:firefoxOptions'].args = [];
       
       // To initialize a Microsoft Edge session with GUI, uncomment the following lines:
       // var opts = Browser.edgeOptions();
       // opts.capabilities.alwaysMatch['ms:edgeOptions'].binary = 'usr/bin/microsoft-edge';
       // opts.capabilities.alwaysMatch['ms:edgeOptions'].args = [];
       
       var browser = new Browser(opts);

If your tests are running on a remote server or in a container, you can use a Virtual Network Computing (VNC) client to connect to the machine's VNC server. This lets you view and interact with the browser's GUI remotely.

Take screenshots

The following script:

  1. Initializes a browser session.
  2. Sets the browser's viewport size to determine the screenshot size (specified as parameters, see below).
  3. Navigates to a URL (specified as a parameter, see below).
  4. Collects session statistics, captures a screenshot, and adds it to the collected statistics.
  5. Handles errors by capturing error messages and a screenshot.
  6. Returns the collected results as a JSON string.

The script also uses parameters from the item configuration form:

  • webURL - http://example.com
  • width - 1920
  • height - 1080

In the Script field, enter:

var browser, result;
       
       var browser = new Browser(Browser.chromeOptions());
       
       try {
           var params = JSON.parse(value); // Parse the JSON string containing parameters passed from Zabbix.
       
           browser.setScreenSize(Number(params.width), Number(params.height))
       
           browser.navigate(params.webURL);
       
           result = browser.getResult();
           result.screenshot = browser.getScreenshot();
       }
       catch (err) {
           if (!(err instanceof BrowserError)) {
               browser.setError(err.message);
           }
           result = browser.getResult();
           result.error.screenshot = browser.getScreenshot();
       }
       finally {
           return JSON.stringify(result);
       }