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

背景

在 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,
      };
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zoe_ya

如果你成功申请,可以打赏杯奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值