Chrome扩展开发:捕获特定URL提取ID并调用Web API
Got it, let's build this Chrome extension step by step. I'll break down each component so you can implement it smoothly, including robust error handling for the Web API calls.
First, you'll need a manifest.json file (required for all Chrome extensions) to define permissions, script targets, and basic extension info. We'll use Manifest V3 (the latest recommended version):
{ "manifest_version": 3, "name": "Office 365 Email ID Extractor", "version": "1.0", "description": "Extracts email IDs from specific profile URLs and calls a Web API", "permissions": ["activeTab", "scripting"], "content_scripts": [ { "matches": ["*://*/profile/office365_emails_email/*"], "js": ["content.js"], "run_at": "document_idle" } ] }
matches: This targets any URL that includes/profile/office365_emails_email/(works across any domain).run_at: Ensures the script runs after the page is fully loaded, so we don't try to parse a URL that hasn't loaded yet.permissions:activeTablets us interact with the current tab, andscriptingallows us to inject scripts if needed (though we're using content scripts here).
Create a content.js file that will run on matching pages. We'll use a regular expression to pull the ID from the URL path:
// Get the current page's URL path const urlPath = window.location.pathname; // Regex to match the ID after /profile/office365_emails_email/ const idRegex = /\/profile\/office365_emails_email\/([a-zA-Z0-9]+)/; const match = urlPath.match(idRegex); if (match && match[1]) { const emailId = match[1]; console.log(`Extracted Email ID: ${emailId}`); // Call the Web API with the extracted ID callWebAPI(emailId); } else { console.warn("No valid email ID found in the URL"); }
The regex ([a-zA-Z0-9]+) captures alphanumeric IDs—adjust this if your IDs include other characters (like underscores or dashes) by updating the character set to [a-zA-Z0-9_-] for example.
Now add the callWebAPI function to handle the API request and all possible failure scenarios:
async function callWebAPI(emailId) { const apiUrl = "https://your-web-api-endpoint.com/process-email"; // Replace with your actual API URL try { const response = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ emailId: emailId }) }); if (!response.ok) { // Handle HTTP errors (4xx, 5xx status codes) throw new Error(`API request failed: ${response.status} ${response.statusText}`); } const data = await response.json(); console.log("API Response:", data); // Optional: Show a success message to the user showUserMessage(`Successfully processed ID: ${emailId}`, "success"); } catch (error) { // Handle all other errors: network issues, JSON parsing failures, etc. console.error("API Call Error:", error.message); // Optional: Show an error message to the user showUserMessage(`Failed to process ID: ${error.message}`, "error"); } } // Helper function to display user messages on the page function showUserMessage(text, type) { const messageEl = document.createElement("div"); messageEl.style.cssText = ` position: fixed; top: 20px; right: 20px; padding: 15px 20px; border-radius: 4px; color: white; font-weight: bold; z-index: 9999; `; messageEl.style.backgroundColor = type === "success" ? "#2ecc71" : "#e74c3c"; messageEl.textContent = text; document.body.appendChild(messageEl); // Auto-remove the message after 5 seconds setTimeout(() => messageEl.remove(), 5000); }
This function handles:
- Network errors: If the API is unreachable (e.g., no internet, server down), the
fetchcall will throw an error caught in thecatchblock. - HTTP errors: Even if the server responds, non-200 status codes (like 404 or 500) are explicitly handled.
- JSON parsing failures: If the API returns invalid JSON,
response.json()will throw an error. - User feedback: The helper function shows a temporary toast message so the user knows what happened (you can customize this styling or remove it if not needed).
To test your extension:
- Open Chrome and go to
chrome://extensions/. - Enable "Developer mode" (toggle in the top-right corner).
- Click "Load unpacked" and select the folder containing your
manifest.jsonandcontent.jsfiles. - Navigate to a URL like
https://example.com/profile/office365_emails_email/abc123456789. - Open the Chrome DevTools (F12) to check the console for logs, and test scenarios like:
- A valid URL with an ID (should extract and call the API).
- A URL without a valid ID (should log a warning).
- An unreachable API (should show an error message and log the issue).
内容的提问来源于stack exchange,提问作者Vinicius Cardoso

