You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展Manifest V3迁移时HTML解析返回[object Object]问题求助

问题原因

Manifest V3 中 chrome.scripting.executeScript 的回调返回值结构,与 Manifest V2 中 chrome.tabs.executeScript 的结构存在本质差异:

  • Manifest V2 的返回值是各注入 frame 执行结果的字符串数组,直接传递给 DOMParser.parseFromString 可以正常解析
  • Manifest V3 的返回值 results 是对象数组,每个元素结构为 {result: 执行返回值, frameId: 帧ID, documentId: 文档ID},你直接将整个 results 对象数组传递给字符串参数的 parseFromString 方法时,数组会被默认转为 [object Object] 格式的字符串,最终解析得到的DOM就出现了问题。

你观察到控制台打印的 results 是预期源码,是因为控制台会完整展示对象结构,你看到的源码实际存储在每个数组元素的 result 字段中,而非 results 本身。


修复方案

从返回的 results 数组中提取每个注入帧的 result 字段,拼接为完整的HTML字符串后再传入解析器即可:

chrome.scripting.executeScript( 
    {
        target: {tabId: tab.id, allFrames: true},
        files: ['GetSource.js'],
    }, async function(results) 
    {
        // 提取所有帧的返回结果,仅需要主框架的话可以直接取 results[0].result
        const pageSource = results.map(frameRes => frameRes.result).join('');
        const parser = new DOMParser();
        const content = parser.parseFromString(pageSource, "text/html");
        console.log(content);   
        // 后续业务逻辑
    }
)

如果偏好更简洁的Promise写法,也可以将逻辑调整为async/await形式:

// 该方法需要放在async函数内执行
const [currentTab] = await chrome.tabs.query({active: true, currentWindow: true});
const injectResults = await chrome.scripting.executeScript({
    target: {tabId: currentTab.id, allFrames: true},
    files: ['GetSource.js']
});
const pageSource = injectResults.map(item => item.result).join('');
const content = new DOMParser().parseFromString(pageSource, "text/html");

内容的提问来源于stack exchange,提问作者Laurent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:48:03