Golang命令行参数启动Chrome的实用指南

Golang命令行参数启动Chrome的实用指南 我正在使用 systrayopen 来在某个URL上打开Chrome浏览器(该URL主要由Go服务器本身提供…),例如:

func main() {
	fmt.Println("Quando Go Server started")
...
	go server.ServeHTTPandIO(handlers)
	systray.Run(onReady, nil)
}

func onReady() {
	systray.SetIcon(icon.Data())
	systray.SetTitle("Quando")
	systray.SetTooltip("Quando - noCode Toolset")
	sysEditor := systray.AddMenuItem("Editor", "Open Editor")
	sysClient := systray.AddMenuItem("Client", "Open Client")
	systray.AddSeparator()
	sysDashboard := systray.AddMenuItem("Dashboard", "Open Dashboard")
	systray.AddSeparator()
	sysGithub := systray.AddMenuItem("Quando:Github", "Open Quando -> Github")
	systray.AddSeparator()
	sysQuit := systray.AddMenuItem("Quit", "Stop the server")
	go func() {
		for {
			select {
			case <-sysQuit.ClickedCh:
				fmt.Println("Exiting...")
				systray.Quit()
			case <-sysEditor.ClickedCh:
				open.StartWith("http://127.0.0.1/editor", "chrome")
			case <-sysClient.ClickedCh:
				open.StartWith("http://127.0.0.1/client", "chrome")
			case <-sysDashboard.ClickedCh:
				open.StartWith("http://127.0.0.1", "chrome")
			case <-sysGithub.ClickedCh:
				open.Start("https://github.com/andrewfstratton/quando")
			}
		}
	}()

但是,似乎没有任何方法可以传入命令行参数——我希望传入 --allow-insecure-localhost

有谁知道是否有(跨平台的)包/选项,类似于 open-lang 的 open,允许将应用程序指定为 Chrome 并且 传递参数 🙂

注意:我知道 lorca 可以做到这一点——但它提供的功能远超过我的需求…我正在考虑从 lorca 中提取 LocateChrome 并使用它…

提前感谢 - Andy


更多关于Golang命令行参数启动Chrome的实用指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

使用 user-data-dir 可以指定不同的配置文件,从而运行一个新的 Chrome 实例。例如(针对 Windows 系统),将之前的示例修改为包含以下内容:

	cmd := exec.Command(loc, "--new-window", "--user-data-dir=C:\\chrome_dir", "--allow-insecure-localhost", "http://127.0.0.1"+suffix)

更多关于Golang命令行参数启动Chrome的实用指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我建议你使用 os/exec 库。你可以这样做:

package main

import (
    "log"
    "os/exec"
)

func main() {
    output, err := exec.Command("chrome", "--allow-insecure-localhost").Output()
    if err != nil {
        log.Fatal(err)
    }

fmt.Println(string(out))
}

感谢 Brandon

我自己也刚刚尝试了那条路线——但使用的是 lorca 来查找 Chrome,因为在 Windows 中 Chrome 默认不在 PATH 中(而且我需要非常简单的部署/设置)。例如:

	loc := lorca.LocateChrome()
	cmd := exec.Command(loc, "--new-window", "--allow-insecure-localhost", "http://127.0.0.1"+suffix)
	err := cmd.Run()
	if err != nil {
		fmt.Println(err)
	}

这部分能工作——即打开一个新窗口——但是,当 Chrome 已经在运行时,它不会启用不安全的本地主机,因为它复用了现有的应用程序。

我想我不得不考虑使用一个配置文件——所以这就变成了一个 Chrome 特定的问题……

谢谢 - Andy

在Go中通过命令行参数启动Chrome,可以使用exec.Command直接调用Chrome可执行文件并传递参数。以下是跨平台解决方案:

package main

import (
    "fmt"
    "os/exec"
    "runtime"
    "strings"
)

// 查找Chrome可执行文件路径(跨平台)
func locateChrome() (string, error) {
    var paths []string
    switch runtime.GOOS {
    case "darwin":
        paths = []string{
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
        }
    case "windows":
        paths = []string{
            os.Getenv("LOCALAPPDATA") + "\\Google\\Chrome\\Application\\chrome.exe",
            os.Getenv("PROGRAMFILES") + "\\Google\\Chrome\\Application\\chrome.exe",
            os.Getenv("PROGRAMFILES(X86)") + "\\Google\\Chrome\\Application\\chrome.exe",
        }
    default: // linux, freebsd, etc.
        paths = []string{
            "google-chrome",
            "google-chrome-stable",
            "google-chrome-unstable",
            "chromium",
            "chromium-browser",
        }
    }

    for _, path := range paths {
        if _, err := os.Stat(path); err == nil {
            return path, nil
        }
    }
    
    // 尝试通过PATH查找
    if runtime.GOOS != "windows" {
        if path, err := exec.LookPath("google-chrome"); err == nil {
            return path, nil
        }
        if path, err := exec.LookPath("chromium"); err == nil {
            return path, nil
        }
    }
    
    return "", fmt.Errorf("Chrome not found")
}

// 使用参数启动Chrome
func openChromeWithArgs(url string, args ...string) error {
    chromePath, err := locateChrome()
    if err != nil {
        return err
    }
    
    cmdArgs := append(args, url)
    cmd := exec.Command(chromePath, cmdArgs...)
    
    // 分离进程,避免阻塞
    if runtime.GOOS == "windows" {
        cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
    } else {
        cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
    }
    
    return cmd.Start()
}

// 在你的systray回调中使用
func onReady() {
    // ... systray设置代码 ...
    
    go func() {
        for {
            select {
            case <-sysEditor.ClickedCh:
                // 传递--allow-insecure-localhost参数
                err := openChromeWithArgs(
                    "http://127.0.0.1/editor",
                    "--allow-insecure-localhost",
                    "--new-window",
                )
                if err != nil {
                    fmt.Printf("Failed to open Chrome: %v\n", err)
                }
                
            case <-sysClient.ClickedCh:
                err := openChromeWithArgs(
                    "http://127.0.0.1/client",
                    "--allow-insecure-localhost",
                    "--new-window",
                )
                if err != nil {
                    fmt.Printf("Failed to open Chrome: %v\n", err)
                }
                
            // ... 其他case处理 ...
            }
        }
    }()
}

如果需要更简洁的封装,可以创建自定义包:

// chrome.go
package chrome

import (
    "os/exec"
    "runtime"
    "syscall"
)

type ChromeLauncher struct {
    Path string
}

func NewChromeLauncher() (*ChromeLauncher, error) {
    path, err := locateChrome()
    if err != nil {
        return nil, err
    }
    return &ChromeLauncher{Path: path}, nil
}

func (c *ChromeLauncher) Open(url string, args ...string) error {
    cmdArgs := append(args, url)
    cmd := exec.Command(c.Path, cmdArgs...)
    
    if runtime.GOOS == "windows" {
        cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
    } else {
        cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
    }
    
    return cmd.Start()
}

// 使用示例
func main() {
    chrome, err := NewChromeLauncher()
    if err != nil {
        panic(err)
    }
    
    // 打开带参数的Chrome
    chrome.Open(
        "http://127.0.0.1:8080",
        "--allow-insecure-localhost",
        "--disable-web-security",
        "--user-data-dir=/tmp/chrome-test",
    )
}

这个方案直接使用exec.Command,可以完全控制Chrome的命令行参数,并且是跨平台的。

回到顶部