automating-chrome

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Automating Chrome / Chromium Browsers (JXA-first, AppleScript discovery)

Chrome/Chromium浏览器自动化(优先使用JXA,结合AppleScript发现功能)

Technology Status

技术现状

JXA/AppleScript browser automation is legacy. JavaScript injection is disabled by default in modern Chrome. Modern alternatives: Selenium/ChromeDriver, Puppeteer, PyXA.
Related Skills:
web-browser-automation
,
automating-mac-apps
PyXA Installation: See
automating-mac-apps
skill (PyXA Installation section).
JXA/AppleScript浏览器自动化属于旧有技术。现代Chrome默认禁用JavaScript注入。现代替代方案:Selenium/ChromeDriver、Puppeteer、PyXA。
相关技能
web-browser-automation
automating-mac-apps
PyXA安装:请查看
automating-mac-apps
技能中的「PyXA安装」章节。

Contents

目录

Scope

适用范围

  • Primary target: Google Chrome (bundle ID: com.google.Chrome).
  • Chromium-based variants (Brave: com.brave.Browser, Edge: com.microsoft.edgemac, Arc: company.thebrowser.Browser) often expose similar dictionaries but may differ by bundle name and permissions.
  • Always verify dictionary availability in Script Editor for target browser before automation.
Security Note: JavaScript injection via AppleScript is disabled by default in Chrome. Enable via: View → Developer → Allow JavaScript from Apple Events (not recommended for production use).
  • 主要目标:Google Chrome(Bundle ID:com.google.Chrome)。
  • 基于Chromium的变体浏览器(Brave:com.brave.Browser、Edge:com.microsoft.edgemac、Arc:company.thebrowser.Browser)通常会暴露类似的字典,但可能在Bundle名称和权限上有所不同。
  • 在进行自动化之前,请务必在脚本编辑器中验证目标浏览器的字典是否可用。
安全提示:Chrome默认禁用通过AppleScript进行JavaScript注入。可通过以下方式启用:视图 → 开发者 → 允许来自Apple事件的JavaScript(不建议在生产环境中使用)。

Core framing

核心框架

  • AppleScript dictionaries define the automation surface.
  • JXA provides logic and data handling.
  • execute()
    runs JavaScript in page context but doesn't reliably return values—use tunneling patterns (save to clipboard/localStorage) for data extraction instead.
⚠️ Security Warning: The tunneling approach (clipboard/localStorage) can expose sensitive data. Use modern APIs for production automation.
  • Tunneling Patterns Explained: Since
    execute()
    doesn't return JavaScript results directly, work around this by having your injected script save data to accessible locations like the system clipboard (
    navigator.clipboard.writeText()
    ) or localStorage (
    localStorage.setItem()
    ). Then retrieve the data in your JXA script using system commands or by reading back from localStorage via another
    execute()
    call.
  • AppleScript字典定义了自动化的可用接口。
  • JXA提供逻辑和数据处理能力。
  • execute()
    方法可在页面上下文中运行JavaScript,但无法可靠返回值——请改用隧道模式(将数据保存到剪贴板/localStorage)来提取数据。
⚠️ 安全警告:隧道方法(剪贴板/localStorage)可能会暴露敏感数据。生产环境自动化请使用现代API。
  • 隧道模式说明:由于
    execute()
    无法直接返回JavaScript执行结果,可通过让注入的脚本将数据保存到系统剪贴板(
    navigator.clipboard.writeText()
    )或localStorage(
    localStorage.setItem()
    )等可访问位置来解决。然后在JXA脚本中通过系统命令或再次调用
    execute()
    读取localStorage中的数据。

Workflow (default)

默认工作流程

  1. Discover dictionary terms in Script Editor (Chrome or target browser).
  2. Prototype minimal AppleScript commands in target browser.
  3. Port to JXA and add defensive checks:
    • Wrap operations in try/catch blocks
    • Check browser process status:
      chrome.running()
    • Verify window/tab indices exist before access
    • Handle permission dialogs programmatically when possible
  4. Use batch URL reads and reverse-order deletes for tab operations.
  5. Use tunneling patterns for DOM data extraction.
  6. Validate results: Log tab counts, URLs, or extracted data to confirm operations succeeded.
  1. 在脚本编辑器中(针对Chrome或目标浏览器)发现字典术语。
  2. 在目标浏览器中编写最小化的AppleScript命令原型。
  3. 移植到JXA并添加防御性检查:
    • 用try/catch块包裹操作
    • 检查浏览器进程状态:
      chrome.running()
    • 在访问前验证标签页/窗口索引是否存在
    • 尽可能以编程方式处理权限对话框
  4. 对标签页操作使用批量URL读取和逆序删除。
  5. 使用隧道模式提取DOM数据。
  6. 验证结果:记录标签页数量、URL或提取的数据以确认操作成功。

Quick Examples

快速示例

Open new tab and navigate:
javascript
const chrome = Application('Google Chrome');
chrome.windows[0].tabs.push(chrome.Tab());
chrome.windows[0].tabs[chrome.windows[0].tabs.length - 1].url = 'https://example.com';
Execute JavaScript in current tab:
javascript
const result = chrome.execute({javascript: 'document.title'});
// Note: execute() runs JS but doesn't reliably return values
Batch close tabs (reverse order):
javascript
const tabs = chrome.windows[0].tabs;
for (let i = tabs.length - 1; i >= 0; i--) {
  if (tabs[i].url().includes('unwanted')) {
    tabs[i].close();
  }
}
Extract page data via tunneling:
javascript
// Inject script to save title to localStorage
chrome.execute({javascript: 'localStorage.setItem("pageTitle", document.title)'});
// Retrieve via another execute call
chrome.execute({javascript: 'console.log(localStorage.getItem("pageTitle"))'});
Check browser permissions:
javascript
try {
  const chrome = Application('Google Chrome');
  chrome.windows[0].tabs[0].url(); // Test access
  console.log('Permissions OK');
} catch (error) {
  console.log('Permission error:', error.message);
}
打开新标签页并导航
javascript
const chrome = Application('Google Chrome');
chrome.windows[0].tabs.push(chrome.Tab());
chrome.windows[0].tabs[chrome.windows[0].tabs.length - 1].url = 'https://example.com';
在当前标签页执行JavaScript
javascript
const result = chrome.execute({javascript: 'document.title'});
// 注意:execute()可运行JS,但无法可靠返回值
批量关闭标签页(逆序)
javascript
const tabs = chrome.windows[0].tabs;
for (let i = tabs.length - 1; i >= 0; i--) {
  if (tabs[i].url().includes('unwanted')) {
    tabs[i].close();
  }
}
通过隧道模式提取页面数据
javascript
// 注入脚本将标题保存到localStorage
chrome.execute({javascript: 'localStorage.setItem("pageTitle", document.title)'});
// 通过再次调用execute()检索数据
chrome.execute({javascript: 'console.log(localStorage.getItem("pageTitle"))'});
检查浏览器权限
javascript
try {
  const chrome = Application('Google Chrome');
  chrome.windows[0].tabs[0].url(); // 测试访问权限
  console.log('Permissions OK');
} catch (error) {
  console.log('Permission error:', error.message);
}

Modern Alternatives

现代替代方案

For production Chrome automation, see the
web-browser-automation
skill for comprehensive guides covering:
  • PyXA: macOS-native Chrome automation with full integration
  • Selenium: Cross-platform automation with automatic ChromeDriver management
  • Puppeteer: Node.js automation with bundled Chrome
  • Multi-browser workflows: Chrome, Edge, Brave, and Arc coordination
Quick PyXA Example (see web-browser-automation skill for details):
python
import PyXA
如需进行生产环境Chrome自动化,请查看
web-browser-automation
技能中的全面指南,涵盖:
  • PyXA:原生macOS Chrome自动化工具,集成度高
  • Selenium:跨平台自动化工具,可自动管理ChromeDriver
  • Puppeteer:Node.js自动化工具,捆绑Chrome浏览器
  • 多浏览器工作流:Chrome、Edge、Brave及Arc浏览器的协同自动化
PyXA快速示例(详情请查看web-browser-automation技能):
python
import PyXA

Launch Chrome and navigate

启动Chrome并导航

chrome = PyXA.Application("Google Chrome") chrome.activate() chrome.open_location("https://example.com")
chrome = PyXA.Application("Google Chrome") chrome.activate() chrome.open_location("https://example.com")

Get current tab info

获取当前标签页信息

current_tab = chrome.current_tab() print(f"Page title: {current_tab.title()}") print(f"Current URL: {current_tab.url()}")
undefined
current_tab = chrome.current_tab() print(f"Page title: {current_tab.title()}") print(f"Current URL: {current_tab.url()}")
undefined

PyObjC with Selenium (Cross-Platform with macOS Integration)

结合PyObjC与Selenium(跨平台且支持macOS集成)

python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from AppKit import NSWorkspace
python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from AppKit import NSWorkspace

Configure Chrome options

配置Chrome选项

options = Options() options.add_argument("--remote-debugging-port=9222") options.add_argument('--headless=new') # Modern headless mode
options = Options() options.add_argument("--remote-debugging-port=9222") options.add_argument('--headless=new') # 现代无头模式

Launch Chrome with Selenium (automatic ChromeDriver management)

通过Selenium启动Chrome(自动管理ChromeDriver)

driver = webdriver.Chrome(options=options) driver.get('https://example.com')
driver = webdriver.Chrome(options=options) driver.get('https://example.com')

macOS integration via PyObjC

通过PyObjC实现macOS集成

workspace = NSWorkspace.sharedWorkspace() frontmost_app = workspace.frontmostApplication() print(f"Frontmost app: {frontmost_app.localizedName()}")
print(f"Page title: {driver.title}") driver.quit()
undefined
workspace = NSWorkspace.sharedWorkspace() frontmost_app = workspace.frontmostApplication() print(f"Frontmost app: {frontmost_app.localizedName()}")
print(f"Page title: {driver.title}") driver.quit()
undefined

Selenium with ChromeDriver (Recommended for Cross-Platform)

Selenium结合ChromeDriver(推荐用于跨平台场景)

bash
undefined
bash
undefined

Install Selenium (latest: 4.38.0)

安装Selenium(最新版本:4.38.0)

pip install selenium
pip install selenium

ChromeDriver is automatically managed by Selenium Manager (v4.11+)

ChromeDriver由Selenium Manager自动管理(v4.11+)

No manual download needed - compatible version downloaded automatically

无需手动下载 - 自动下载兼容版本

Basic Python example

Python基础示例

from selenium import webdriver
driver = webdriver.Chrome() # Automatic ChromeDriver management driver.get('https://example.com') print(driver.title) driver.quit()

**Advanced Configuration:**
```python
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless=new')  # Modern headless mode (required)
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=options)
driver.get('https://example.com')
print(f"Page title: {driver.title}")
driver.quit()
Manual ChromeDriver Setup (for specific versions):
python
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
driver = webdriver.Chrome() # 自动管理ChromeDriver driver.get('https://example.com') print(driver.title) driver.quit()

**高级配置**:
```python
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless=new')  # 现代无头模式(必填)
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Chrome(options=options)
driver.get('https://example.com')
print(f"Page title: {driver.title}")
driver.quit()
手动ChromeDriver配置(针对特定版本)
python
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

Match major version with your Chrome installation

版本号需与你的Chrome安装版本主版本号匹配

service = Service(executable_path='/path/to/chromedriver') options = Options() driver = webdriver.Chrome(service=service, options=options)

**Note**: Selenium 4.11+ automatically downloads compatible ChromeDriver. Manual setup only needed for specific version requirements or CI/CD environments.
service = Service(executable_path='/path/to/chromedriver') options = Options() driver = webdriver.Chrome(service=service, options=options)

**注意**:Selenium 4.11+会自动下载兼容的ChromeDriver。仅在需要特定版本或CI/CD环境中才需手动配置。

Puppeteer (Recommended for Node.js)

Puppeteer(推荐用于Node.js场景)

bash
undefined
bash
undefined

Install Puppeteer (latest: 24.35.0)

安装Puppeteer(最新版本:24.35.0)

npm install puppeteer
npm install puppeteer

Bundles compatible Chrome automatically

自动捆绑兼容的Chrome浏览器


```javascript
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: 'new'  // Modern headless mode (required in v24+)
  });
  const page = await browser.newPage();
  await page.goto('https://example.com');
  const title = await page.title();
  console.log(title);
  await browser.close();
})();
Advanced Puppeteer Configuration:
javascript
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-dev-shm-usage']
  });
  const page = await browser.newPage();

  // Set viewport
  await page.setViewport({ width: 1280, height: 720 });

  await page.goto('https://example.com');

  // Wait for element and interact
  await page.waitForSelector('h1');
  const title = await page.title();

  console.log(`Page title: ${title}`);
  await browser.close();
})();

```javascript
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: 'new'  // 现代无头模式(v24+必填)
  });
  const page = await browser.newPage();
  await page.goto('https://example.com');
  const title = await page.title();
  console.log(title);
  await browser.close();
})();
Puppeteer高级配置
javascript
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-dev-shm-usage']
  });
  const page = await browser.newPage();

  // 设置视口
  await page.setViewport({ width: 1280, height: 720 });

  await page.goto('https://example.com');

  // 等待元素加载并交互
  await page.waitForSelector('h1');
  const title = await page.title();

  console.log(`Page title: ${title}`);
  await browser.close();
})();

Chrome DevTools Protocol (Advanced)

Chrome DevTools Protocol(高级用法)

javascript
// WebSocket connection to CDP
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:9222/devtools/page/{page-id}');

// Send CDP commands
ws.send(JSON.stringify({
  id: 1,
  method: 'Runtime.evaluate',
  params: { expression: 'document.title' }
}));
Setup Requirements:
  • ChromeDriver: Download from Chrome for Testing
  • Puppeteer:
    npm install puppeteer
  • CDP: Launch Chrome with
    --remote-debugging-port=9222
javascript
// 通过WebSocket连接到CDP
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:9222/devtools/page/{page-id}');

// 发送CDP命令
ws.send(JSON.stringify({
  id: 1,
  method: 'Runtime.evaluate',
  params: { expression: 'document.title' }
}));
配置要求
  • ChromeDriver:从Chrome for Testing下载
  • Puppeteer:
    npm install puppeteer
  • CDP:启动Chrome时添加参数
    --remote-debugging-port=9222

Validation Checklist

验证清单

  • Browser automation permissions granted (System Settings > Privacy & Security)
  • Chrome running and accessible:
    chrome.running()
    returns true
  • JavaScript injection enabled (View > Developer > Allow JavaScript from Apple Events)
  • Tab/window indices verified before access
  • Error handling wraps all operations
  • Data extraction via tunneling confirmed
  • Results logged and validated
  • 已授予浏览器自动化权限(系统设置 > 隐私与安全性)
  • Chrome正在运行且可访问:
    chrome.running()
    返回true
  • 已启用JavaScript注入(视图 > 开发者 > 允许来自Apple事件的JavaScript)
  • 访问前已验证标签页/窗口索引
  • 所有操作都包含错误处理
  • 已确认通过隧道模式提取数据
  • 已记录并验证结果

When Not to Use

不适用场景

  • Cross-platform browser automation (use Selenium or Playwright)
  • Production web scraping or testing (use ChromeDriver/Puppeteer)
  • JavaScript injection disabled (default in modern Chrome)
  • Non-macOS platforms
  • Heavy DOM manipulation (use Puppeteer/Playwright)
  • 跨平台浏览器自动化(请使用Selenium或Playwright)
  • 生产环境网页抓取或测试(请使用ChromeDriver/Puppeteer)
  • JavaScript注入被禁用(现代Chrome默认状态)
  • 非macOS平台
  • 大量DOM操作(请使用Puppeteer/Playwright)

What to load

需加载的资源

  • Chrome JXA basics:
    automating-chrome/references/chrome-basics.md
  • Recipes (tabs, URLs, windows):
    automating-chrome/references/chrome-recipes.md
  • Advanced patterns (execute tunneling, incognito):
    automating-chrome/references/chrome-advanced.md
  • Dictionary translation table:
    automating-chrome/references/chrome-dictionary.md
  • Browser name mapping:
    automating-chrome/references/chromium-browser-names.md
  • Form automation basics:
    automating-chrome/references/chrome-form-automation.md
Related Skills for Modern Chrome Automation:
  • web-browser-automation
    : Complete guide for Chrome, Edge, Brave, and Arc automation
  • automating-mac-apps
    : PyXA fundamentals and conversion guides
  • Chrome JXA基础:
    automating-chrome/references/chrome-basics.md
  • 实用脚本(标签页、URL、窗口):
    automating-chrome/references/chrome-recipes.md
  • 高级模式(execute隧道、隐身窗口):
    automating-chrome/references/chrome-advanced.md
  • 字典转换表:
    automating-chrome/references/chrome-dictionary.md
  • 浏览器名称映射:
    automating-chrome/references/chromium-browser-names.md
  • 表单自动化基础:
    automating-chrome/references/chrome-form-automation.md
现代Chrome自动化相关技能
  • web-browser-automation
    :Chrome、Edge、Brave及Arc浏览器自动化完整指南
  • automating-mac-apps
    :PyXA基础及转换指南