如何在Chrome扩展程序中复制当前页面的HTML内容?
Hey there, let's figure out why your jQuery code isn't working in the popup and fix it. The core issue here is context isolation—your popup's JavaScript runs in its own separate environment, completely disconnected from the DOM of the third-party website you're trying to scrape. That's why $(".abc").clone().html() works in a regular page but not in your popup.js.
Step 1: Fix Your Manifest.json
First, you've got a mistake in your manifest—you're loading popup.js as a content script, but popup.js should be tied to your popup.html instead. Content scripts are injected into the target website's context, while popup.js runs in the popup's isolated context. Let's correct that:
Update your manifest to use a separate content script file (let's call it content.js) instead of popup.js:
{ "manifest_version": 2, "name": "WGCE", "version": "1.0", "description": "App Description", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": [ "cookies", "tabs", "http://*/*", "https://*/*" ], "content_scripts": [{ "js": ["content.js"], // Replace popup.js with content.js here // Add jQuery if you want to use it: "js": ["jquery.js", "content.js"], "matches": ["https://example.com/*"] }] }
Step 2: Create the Content Script (content.js)
Content scripts live in the target website's context, so they can access its DOM directly. We'll use this script to grab the HTML of .abc and send it back to the popup when requested.
If you prefer vanilla JS (no jQuery):
// content.js chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === "getTargetHtml") { const targetElement = document.querySelector(".abc"); if (targetElement) { // Clone the element and get its full HTML (including the element itself) const clonedHtml = targetElement.cloneNode(true).outerHTML; sendResponse({ html: clonedHtml }); } else { sendResponse({ html: null, error: "Element .abc not found" }); } } return true; // Keep the message channel open for async responses });
If you want to use jQuery (make sure you include the jQuery library in your extension files and add it to the content_scripts.js array in manifest):
// content.js (with jQuery) chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === "getTargetHtml") { const clonedHtml = $(".abc").clone().html(); sendResponse({ html: clonedHtml }); } return true; });
Step 3: Update popup.js to Request the HTML
Now, your popup needs to send a message to the content script running in the active tab, asking for the HTML. We'll use Chrome's tabs API to do this:
// popup.js document.addEventListener('DOMContentLoaded', () => { // Get the active tab in the current window chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { // Send a message to the content script in that tab chrome.tabs.sendMessage(tabs[0].id, { action: "getTargetHtml" }, (response) => { if (response && response.html) { // Do something with the HTML—like copy it to clipboard! console.log("Fetched HTML:", response.html); // Copy to clipboard navigator.clipboard.writeText(response.html) .then(() => alert("HTML copied to clipboard!")) .catch(err => console.error("Failed to copy:", err)); } else { alert(response?.error || "Failed to fetch HTML"); } }); }); });
Step 4: Link popup.js to popup.html
Make sure your popup.html references popup.js correctly:
<!-- popup.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WGCE Popup</title> <script src="popup.js"></script> </head> <body> <!-- Add your popup UI elements here (like a button to trigger the copy) --> </body> </html>
Why This Works
- Content Script: Runs directly inside the target website, so it can access the DOM and grab the
.abcelement's HTML. - Message Passing: Chrome's runtime messaging API lets the popup (isolated context) communicate with the content script (website context) to exchange data.
- Clipboard Access: The popup has permission to use the Clipboard API by default, so once you receive the HTML, you can copy it easily.
内容的提问来源于stack exchange,提问作者Tasaddaq Rana

