开发Chrome扩展:需检测OBS运行以屏蔽敏感信息,是否可行?
Great question! Let's break this down clearly—since you're building a Chrome extension to shield sensitive data when OBS is running, we need to work within Chrome's security constraints while finding a reliable solution.
The short answer is yes, but not directly out of the box. Chrome's sandboxed environment blocks extensions from accessing local system resources (like process lists) by default to protect user security. That said, there are two main, supported ways to pull this off.
1. Native Messaging (Most reliable, official Chrome API)
This is the recommended approach because it lets your extension communicate with a small local script/program that can check for OBS processes. Here's how to set it up:
Step 1: Build a local process detector script
You can write this in Python, PowerShell, or any language that can read system processes. Below are cross-platform examples:
Python script (works on Windows/macOS/Linux)
Requires the psutil package (pip install psutil):
import sys import json import psutil def is_obs_running(): # Check for common OBS process names across platforms obs_processes = {"obs.exe", "obs64.exe", "obs", "OBS"} for proc in psutil.process_iter(["name"]): try: if proc.info["name"] in obs_processes: return True except (psutil.NoSuchProcess, psutil.AccessDenied): continue return False # Send response to Chrome extension (must be JSON + newline) response = {"running": is_obs_running()} sys.stdout.write(json.dumps(response) + "\n") sys.stdout.flush()
PowerShell script (Windows-only)
# Check for OBS 64-bit process (most common on Windows) $obsProcess = Get-Process -Name "obs64" -ErrorAction SilentlyContinue if ($obsProcess) { Write-Host '{"running": true}' } else { Write-Host '{"running": false}' }
Step 2: Configure Native Messaging for your extension
You need two things:
- Update your extension's
manifest.jsonto include thenativeMessagingpermission:
{ "manifest_version": 3, "name": "OBS Sensitive Data Shield", "version": "1.0", "permissions": ["nativeMessaging"], "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ] }
- Create a local manifest file (e.g.,
com.yourdomain.obsdetector.json) that tells Chrome where your script lives. Place this file in the correct location for your OS:- Windows: Register it in the Registry at
HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.yourdomain.obsdetector(point to the JSON file path) - macOS:
~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.yourdomain.obsdetector.json - Linux:
~/.config/google-chrome/NativeMessagingHosts/com.yourdomain.obsdetector.json
- Windows: Register it in the Registry at
Local manifest content:
{ "name": "com.yourdomain.obsdetector", "description": "Detects if OBS is running", "path": "/full/path/to/your/script.py", "type": "stdio", "allowed_origins": ["chrome-extension://YOUR_EXTENSION_ID/"] }
Replace YOUR_EXTENSION_ID with your extension's actual ID (find it in Chrome's extension management page when developer mode is on).
Step 3: Add code to your extension to communicate with the script
In your background service worker (background.js):
// Connect to the native messaging host const port = chrome.runtime.connectNative("com.yourdomain.obsdetector"); // Send a request to check OBS status port.postMessage({ action: "check_obs" }); // Handle the response port.onMessage.addListener((response) => { if (response.running) { console.log("OBS is active—shielding sensitive data!"); // Send a message to your content script to hide sensitive elements chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, { shieldSensitive: true }); }); } else { console.log("OBS is not running—no action needed."); chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, { shieldSensitive: false }); }); } }); // Handle disconnections port.onDisconnect.addListener(() => { console.error("Native messaging disconnected:", chrome.runtime.lastError); });
Then in your content script (content.js), add logic to show/hide sensitive data:
chrome.runtime.onMessage.addListener((message) => { if (message.shieldSensitive) { // Example: Hide login forms and profile info document.querySelectorAll('input[type="password"], .user-profile').forEach(el => { el.style.visibility = "hidden"; // Or replace with a placeholder: el.innerHTML = "[Sensitive content hidden while OBS is running]"; }); } else { // Restore visibility document.querySelectorAll('input[type="password"], .user-profile').forEach(el => { el.style.visibility = "visible"; }); } });
2. OBS WebSocket (No local script required, but less reliable)
If your users have OBS's built-in WebSocket server enabled (available in OBS 28+ by default), you can have your extension try connecting to it. If the connection succeeds, OBS is running.
Example code in your extension:
async function checkOBSWebSocket() { try { const ws = new WebSocket("ws://localhost:4455"); // Default OBS WebSocket port ws.onopen = () => { console.log("OBS detected via WebSocket!"); // Trigger your shielding logic here ws.close(); }; ws.onerror = () => { console.log("OBS not running or WebSocket disabled."); }; } catch (err) { console.error("Error checking OBS WebSocket:", err); } } // Check every 30 seconds to keep status updated setInterval(checkOBSWebSocket, 30000);
Note: This depends on users having WebSocket enabled in OBS settings, and if they set a password for WebSocket access, you'll need to handle authentication in your connection code. It's simpler for users but less reliable than Native Messaging.
- Cross-platform support: Make sure your process detector script accounts for different OBS process names (e.g.,
obs64.exeon Windows,obson Linux,OBSon macOS). - User installation: For Native Messaging, users will need to manually install your local script and register the manifest—you'll need to provide clear setup instructions with your extension.
- Chrome security: Never ask users to disable Chrome's security features; stick to official APIs like Native Messaging.
内容的提问来源于stack exchange,提问作者JPlusPlus

