You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS下如何用Node.js将Selenium打开的Chrome窗口移至第三显示器?

在MacOS下通过Node.js自动化将Selenium打开的Chrome窗口移至另一显示器

以下是三种可行的解决方案,按可靠性和易用性排序:

方案一:通过Chrome启动参数直接指定窗口位置

这是最直接的方式,利用Chrome内置的启动参数--window-position和--window-size,在启动时就将窗口定位到第二显示器。

步骤:

  1. 获取第二显示器的坐标与尺寸(MacOS中主显示器通常为(0,0),第二显示器的坐标取决于排列方式,可能是正偏移或负偏移)
  2. 在Selenium的ChromeOptions中添加对应参数

代码示例:

const { execSync } = require('child_process');
const { Builder, Options } = require('selenium-webdriver');

// 获取第二显示器的位置和尺寸
function getSecondDisplayInfo() {
  const appleScript = `
    tell application "System Events"
      set displays to every desktop
      if (count of displays) > 1 then
        set secondDisplay to item 2 of displays
        return {position of secondDisplay, size of secondDisplay}
      else
        return null
      end if
    end tell
  `;
  const output = execSync(`osascript -e '${appleScript.replace(/\n/g, ' ')}'`).toString().trim();
  if (!output) return null;

  const [posPart, sizePart] = output.split(', ');
  const [x, y] = posPart.replace(/[{}]/g, '').split(',').map(Number);
  const [width, height] = sizePart.replace(/[{}]/g, '').split(',').map(Number);
  return { x, y, width, height };
}

async function launchChromeOnSecondDisplay() {
  const secondDisplay = getSecondDisplayInfo();
  if (!secondDisplay) {
    console.error('未检测到第二显示器');
    return;
  }

  const { x, y, width, height } = secondDisplay;
  const chromeOptions = new Options();
  // 指定窗口位置和尺寸
  chromeOptions.addArguments(`--window-position=${x},${y}`);
  chromeOptions.addArguments(`--window-size=${width},${height}`);
  // 可选:启动时最大化窗口
  chromeOptions.addArguments('--start-maximized');

  // 启动Chrome并连接Selenium
  const driver = await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(chromeOptions)
    .build();

  // 后续测试逻辑
  await driver.get('https://example.com');
}

launchChromeOnSecondDisplay();

方案二:通过Chrome DevTools Protocol动态调整窗口位置

利用Selenium对Chrome DevTools的支持,调用Browser.setWindowBoundsAPI动态修改窗口位置,适合需要在测试过程中移动窗口的场景。

代码示例:

const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

// 复用方案一中的getSecondDisplayInfo函数
function getSecondDisplayInfo() { /* ... 同上 ... */ }

async function moveChromeWindowToSecondDisplay() {
  // 启动Chrome
  const driver = await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(new chrome.Options())
    .build();

  // 初始化DevTools会话
  const devTools = await driver.createDevTools();
  await devTools.send('Browser.enable');

  const secondDisplay = getSecondDisplayInfo();
  if (secondDisplay) {
    const { x, y, width, height } = secondDisplay;
    // 获取当前窗口ID并设置位置
    const windowId = (await devTools.send('Browser.getWindowForTarget')).windowId;
    await devTools.send('Browser.setWindowBounds', {
      windowId,
      bounds: {
        left: x,
        top: y,
        width: width,
        height: height,
        windowState: 'normal'
      }
    });
  }

  // 后续测试逻辑
  await driver.get('https://example.com');
}

moveChromeWindowToSecondDisplay();

方案三:改进AppleScript定位并移动窗口

如果前两种方案无法满足需求,可以优化AppleScript的窗口定位逻辑,避免误操作后台窗口。

关键改进点:

  • 给Selenium启动的Chrome设置独立用户目录,避免与其他Chrome实例混淆
  • 通过窗口标题精准定位目标窗口
  • 动态获取"Move to"菜单选项,避免硬编码显示器名称

代码示例:

const { execSync } = require('child_process');
const { Builder, Options } = require('selenium-webdriver');

async function moveWithAppleScript() {
  // 启动独立Chrome实例
  const profileDir = '/tmp/selenium-chrome-test-profile';
  const chromeOptions = new Options();
  chromeOptions.addArguments(`--user-data-dir=${profileDir}`);
  chromeOptions.addArguments('--window-title=SeleniumTestWindow'); // 设置唯一窗口标题

  const driver = await new Builder()
    .forBrowser('chrome')
    .setChromeOptions(chromeOptions)
    .build();

  // 等待窗口完全加载
  await driver.sleep(2000);

  // 动态获取并点击"Move to"第二个显示器的菜单选项
  const appleScript = `
    tell application "Google Chrome"
      set targetWindow to first window whose title contains "SeleniumTestWindow"
      activate targetWindow
      tell application "System Events"
        tell process "Google Chrome"
          set windowMenu to menu "Window" of menu bar 1
          set moveItems to every menu item of windowMenu whose name starts with "Move to"
          if (count of moveItems) > 1 then
            click item 2 of moveItems
          end if
        end tell
      end tell
    end tell
  `;

  try {
    execSync(`osascript -e '${appleScript.replace(/\n/g, ' ')}'`);
  } catch (err) {
    console.error('移动窗口失败:', err.message);
  }

  // 后续测试逻辑
  await driver.get('https://example.com');
}

moveWithAppleScript();

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 14:47:39