Chrome扩展开发:黑名单域名页面暂停加载与恢复访问实现
Got it, let's build this Chrome extension step by step—here's a complete, tested implementation that covers all your requirements:
Core Implementation Logic
The extension works in 3 key steps:
- Listen for tab loading events in the background
- Check if the tab's domain is in your blacklist
- If it is, inject a content script to pause loading and show a warning; let users reload the page if they choose to proceed
Full Code Breakdown
1. Manifest File (manifest.json)
We'll use Manifest V3 (the latest standard for Chrome extensions) with required permissions:
{ "manifest_version": 3, "name": "Unsafe Site Blocker", "version": "1.0", "description": "Blocks access to unsafe sites and displays a warning prompt", "permissions": ["tabs", "scripting", "storage"], "background": { "service_worker": "background.js" }, "icons": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }
Note: Replace the icon paths with your own assets, or remove them if you don't need custom icons.
2. Background Service Worker (background.js)
This handles domain checking and script injection:
// Example blacklist—you can make this editable via a popup later const blacklist = ["example.com", "malicious-site.com"]; // Helper to extract domain from URL function getDomain(url) { try { return new URL(url).hostname; } catch (err) { return null; } } // Listen for tab loading events chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => { // Only check when the page starts loading (skip cached/already loaded pages) if (changeInfo.status === "loading" && tab.url.startsWith("http")) { const domain = getDomain(tab.url); if (!domain) return; // Check if user previously allowed this domain temporarily const tempAllow = await chrome.storage.local.get(`allowed_${domain}`); if (tempAllow[`allowed_${domain}`]) return; // Block if domain is in blacklist if (blacklist.includes(domain)) { try { await chrome.scripting.executeScript({ target: { tabId }, files: ["content.js"] }); } catch (err) { console.error("Failed to inject blocking script:", err); } } } }); // Handle temporary access requests from content script chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => { if (message.action === "allowDomain") { // Allow domain for the current browser session await chrome.storage.local.set({ [`allowed_${message.domain}`]: true }); } });
3. Content Script (content.js)
This pauses page loading and replaces the page with your warning:
// Immediately stop the page from loading any resources window.stop(); // Build the warning UI const warningPage = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>⚠️ 页面不安全提示</title> <style> body { font-family: system-ui, -apple-system, sans-serif; background: #ffebee; min-height: 100vh; display: flex; align-items: center; justify-content: center; margin: 0; padding: 20px; } .warning-card { background: white; padding: 4rem; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.15); text-align: center; max-width: 500px; } h1 { color: #c62828; margin: 0 0 1rem; } p { color: #424242; font-size: 1.1rem; margin: 0 0 2rem; } .proceed-btn { background: #c62828; color: white; border: none; padding: 0.8rem 2rem; font-size: 1rem; border-radius: 6px; cursor: pointer; transition: background 0.2s; } .proceed-btn:hover { background: #b71c1c; } </style> </head> <body> <div class="warning-card"> <h1>此页面不安全!</h1> <p>该网站已被列入黑名单,可能存在安全风险。</p> <button class="proceed-btn" id="proceed">坚持访问</button> </div> <script> document.getElementById('proceed').addEventListener('click', async () => { // Request background to temporarily allow this domain await chrome.runtime.sendMessage({ action: "allowDomain", domain: window.location.hostname }); // Reload to access the original page window.location.reload(); }); </script> </body> </html> `; // Replace the entire page with the warning UI document.open(); document.write(warningPage); document.close();
Key Notes
- Pausing Page Load:
window.stop()instantly halts all resource loading, ensuring the blacklisted site can't render any content before our warning shows up. - Temporary Allowance: The extension uses Chrome's
storage.localto remember if a user chose to proceed with a site—this persists until the browser is closed (you can adjust this to persist longer if needed). - Customization: You can easily modify the blacklist, warning UI styling, or add features like a popup to let users manage the blacklist.
内容的提问来源于stack exchange,提问作者Kalagar




