如何通过Chrome扩展弹窗获取当前网页的document.body?
document.body in Your Chrome Extension Ah, I get it—you're running into the classic popup vs. active tab context issue! The popup is its own isolated HTML document, so when you call document.body in your popup's app.js, you're only accessing the popup's own DOM, not the webpage you're viewing. Let's fix this with Chrome's extension APIs.
Why This Happens
Your popup runs in a separate sandboxed environment, completely independent of the active tab's webpage. So any references to document in the popup's script will always point to the popup's DOM, not the target page.
The Solution: Inject Scripts into the Active Tab
Since you already have the activeTab permission in your manifest.json (great call!), we can use chrome.tabs.executeScript to run code directly in the context of the active webpage. This injected script will have full access to the page's document object, and we can send the data back to the popup.
Modified Code
First, your manifest.json is already good to go—keep it as is, since activeTab gives us the temporary permission we need when the user clicks the extension icon.
Now update your popup/app.js to this:
function main() { // Execute a script directly in the active tab's context chrome.tabs.executeScript({ code: ` // This code runs INSIDE the active webpage, not the popup const pageBody = document.body; const pageTitle = document.title; // Return the data we need back to the popup { body: pageBody, title: pageTitle } ` }, (results) => { // Handle the data sent back from the injected script if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError); return; } const { body, title } = results[0]; console.log('Active tab\'s document.body:', body); // Update the popup with the page's title const titleElement = document.createElement('div'); titleElement.textContent = title; // Use textContent instead of innerHTML for safety document.body.appendChild(titleElement); }); } main();
What's Changed?
chrome.tabs.executeScript: This API injects the code string into the active tab. The code runs in the webpage's context, sodocumenthere refers to the target page's DOM.- Data Return: The injected script returns an object with the page's
bodyandtitle, which we receive in the popup's callback function (viaresults[0]). - Safety Note: I swapped
innerHTMLfortextContentwhen setting the title—this prevents any accidental XSS if the page title has malicious HTML.
Testing It
- Reload your extension in Chrome's extensions page (chrome://extensions/)
- Navigate to any webpage
- Click your extension icon—you'll now see the webpage's title in the popup, and the console will log the target page's
document.body(check the popup's dev tools: right-click the popup and select "Inspect")
内容的提问来源于stack exchange,提问作者deadcoder0904

