代码之家  ›  专栏  ›  技术社区  ›  Jankapunkt

打开时设置目标。通过MacOS上的终端发送html文件

  •  1
  • Jankapunkt  · 技术社区  · 7 年前

    this solved topic 关于打开。通过命令行创建html文件。

    我使用了该解决方案,而且使用起来效果很好

    open ./myfile.html
    

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

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

    所有剩余的参数都将传递给中打开的应用程序 argv参数到main()。这些参数未打开或 由打开工具解释。

    因此,我尝试了以下方法:

    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
    

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

    编辑:就目前而言,这足以让chrome发挥作用。

    1 回复  |  直到 7 年前
        1
  •  3
  •   CJK    7 年前

    这个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