create-react-app如何复用已有浏览器标签?附OS X下osascript疑问
嘿,这个问题我刚好摸过门道,给你掰扯清楚哈~
CRA复用浏览器标签的实现原理
create-react-app能复用已有标签,背后靠的是react-scripts包里的openBrowser.js模块。在OS X上,它本质是通过一段AppleScript脚本实现智能判断:
- 先遍历Chrome的所有窗口和标签页,检查有没有打开目标URL(比如
http://localhost:8080)的标签 - 要是找到匹配的,就立刻激活对应的Chrome窗口,并切换到那个标签页
- 没找到的话,才会乖乖新开一个标签页
给你看个简化版的核心脚本逻辑,大概就是这个路子:
tell application "Google Chrome" set targetUrl to "%s" # 这里会被替换成实际要打开的URL set found to false repeat with w in windows repeat with t in tabs of w if URL of t starts with targetUrl then set active tab index of w to index of t set index of w to 1 # 把窗口提到最前面 set found to true exit repeat end if end repeat if found then exit repeat end repeat if not found then open location targetUrl end if end tell
OS X上osascript的正确使用方法
你之前的命令报错,主要是没搞对脚本的传递方式或者参数处理。给你两种靠谱的用法:
方式一:直接在命令行跑脚本片段
用-e参数把AppleScript代码直接传给osascript,比如要实现和CRA一样的复用效果,直接执行这条命令就行:
osascript -e 'tell application "Google Chrome" set targetUrl to "http://localhost:8080" set found to false repeat with w in windows repeat with t in tabs of w if URL of t starts with targetUrl then set active tab index of w to index of t set index of w to 1 set found to true exit repeat end if end repeat if found then exit repeat end repeat if not found then open location targetUrl end if end tell'
方式二:通过脚本文件执行
如果你把脚本存成了openChrome.applescript,得先给脚本加上接收参数的逻辑,修改后的脚本内容如下:
on run argv set targetUrl to item 1 of argv # 接收命令行传入的第一个参数 tell application "Google Chrome" set found to false repeat with w in windows repeat with t in tabs of w if URL of t starts with targetUrl then set active tab index of w to index of t set index of w to 1 set found to true exit repeat end if end repeat if found then exit repeat end repeat if not found then open location targetUrl end if end tell end run
然后执行的时候,把完整URL作为参数传进去:
osascript openChrome.applescript "http://localhost:8080"
⚠️ 注意一定要传完整的URL(带http://),不然脚本里的匹配逻辑可能失效哦~
内容的提问来源于stack exchange,提问作者Raphael Rafatpanah
相关产品推荐
相关产品推荐

