在 node 端执行打开一个新的 chrome 并且跳转到指定 url

发布于:2025-07-13 ⋅ 阅读:(19) ⋅ 点赞:(0)

背景

在 node 端执行打开一个新的 chrome 浏览器 并且跳转到指定 url

注意不是在原有浏览器打开新页签

代码

talking is cheap, show me the code

  @Get('/url')
  async getUser(@Query('url') url: string): Promise<any> {
    try {
      if (!url) {
        return {
          success: false,
          error: 'URL参数不能为空',
        };
      }

      let targetUrl = url;
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        targetUrl = `https://${url}`;
      }

      const isWin = process.platform === 'win32';
      const isMac = process.platform === 'darwin';
      const isLinux = process.platform === 'linux';

      let command: string;
      if (isMac) {
        command = `osascript -e 'tell application "Google Chrome" to make new window' -e 'tell application "Google Chrome" to set URL of active tab of front window to "${targetUrl}"'`;
      } else if (isWin) {
        command = `start chrome --new-window "${targetUrl}"`;
      } else if (isLinux) {
        command = `google-chrome --new-window "${targetUrl}"`;
      } else {
        return {
          success: false,
          error: '不支持的操作系统',
        };
      }

      exec(command, (error, stdout, stderr) => {
        if (error) {
          console.error('打开Chrome失败:', error);
        }
        if (stderr) {
          console.error('Chrome错误输出:', stderr);
        }
        if (stdout) {
          console.log('Chrome输出:', stdout);
        }
      });

      return {
        success: true,
        url: targetUrl,
        message: '正在打开Chrome浏览器...',
      };
    } catch (error) {
      return {
        success: false,
        error: error.message,
      };
    }
  }

网站公告

今日签到

点亮在社区的每一天
去签到