1

有关于通过命令行打开 .html 文件的已解决主题。

我使用该解决方案,它适用于使用

open ./myfile.html

但是,它始终在新选项卡中打开文件。我想始终在同一个选项卡中打开它(使用浏览器目标)。这在 JavaScript 中是很容易做到的,但我想不出结合上述代码的方法来做到这一点。

我现在的假设是,必须有一种方法可以将目标作为参数传递给 open 命令。man open揭示了参数的以下内容--args

所有剩余的参数都在 main() 的 argv 参数中传递给打开的应用程序。open 工具不会打开或解释这些参数。

所以我尝试了以下方法:

open ./myfile.html --args target=myfile_target   # still opens in new tab
open ./myfile.html --args target="myfile_target" # still opens in new tab
open ./myfile.html --args target:myfile_target   # still opens in new tab

我不确定这是否有效,但我认为必须有办法做到这一点。

编辑:现在它足以使这个工作与铬。

4

1 回答 1

2

这个 Bash 脚本包含了一些 AppleScript,以便打开一个浏览器窗口,其中包含脚本可以跟踪的引用并继续以正在进行的 URL 请求为目标。

您应该能够将其复制粘贴到文本编辑器中并将其保存为您希望调用此替换open函数的任何内容。我将其另存为url, 在我的$PATH变量中列出的目录之一中。这样,我可以简单地url dropbox.com从命令行键入,它就会运行。

您必须先使其可执行,然后才能执行此操作。因此,保存后,运行以下命令:

chmod +x /path/to/file

那么你应该很高兴。如果您遇到任何错误,请告诉我,我会修复它们。

    #!/bin/bash
    #
    # Usage: url %file% | %url%
    #
    # %file%: relative or absolute POSIX path to a local .html file
    # %url%: [http[s]://]domain[/path/etc...]

    IFS=''

    # Determine whether argument is file or web address
    [[ -f "$1" ]] && \
        _URL=file://$( cd "$( dirname "$1" )"; pwd )/$( basename "$1" ) || \
            { [[ $1 == http* ]] && _URL=$1 || _URL=http://$1; };

    # Read the value on the last line of this script
    _W=$( tail -n 1 "$0" )

    # Open a Safari window and store its AppleScript object id reference
    _W=$( osascript \
        -e "use S : app \"safari\"" \
        -e "try" \
        -e "    set S's window id $_W's document's url to \"$_URL\"" \
        -e "    return $_W" \
        -e "on error" \
        -e "    S's (make new document with properties {url:\"$_URL\"})" \
        -e "    return id of S's front window" \
        -e "end try" )

    _THIS=$( sed \$d "$0" ) # All but the last line of this script
    echo "$_THIS" > "$0"    # Overwrite this file
    echo -n "$_W" >> "$0"   # Appened the object id value as final line

    exit
    2934
于 2018-02-07T02:40:58.340 回答