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

Chrome扩展中Promise回调内修改闭包DOM元素失效问题

问题:Chrome扩展异步回调内DOM元素isConnected为false,无法更新页面内容

我正在开发一款Chrome扩展,用来修改网站内容——通过后台脚本调用后端API获取数据后更新页面内容。最初发现修改元素innerHTML后页面毫无变化,调试后发现Promise回调函数里element.isConnected为false。

具体场景:读取表格行数据,API返回后更新对应单元格,将表格行存入数组并通过map函数处理。

初始代码(await版本)

let tableRows = document.querySelectorAll(".tablerow");
let tableRowsArray = Array.from(tableRows);
tableRowsArray.map(function (row) {
  let tableCells = row.innerHTML.split("</td>");
  (async () => {
    console.log(row.isconnected);                         // 此处返回true
    const response = await chrome.runtime.sendMessage(/*{some data}*/);
    let fetcheda = response.a;
    tableCells.splice(12, 0, "<td><output>" + fetcheda + "</output></td>");
    console.log(row.isConnected);                         // 此处返回false
    row.innerHTML = tableCells.join("");
    console.log(row);                                     // 行元素已被正确修改,但页面无变化
  })();
});

尝试过的方案

  • 用.then()替代await,问题依旧
  • 将chrome.runtime.sendMessage()替换为超时Promise,问题未解决

.then()版本代码

let tableRows = document.querySelectorAll(".tablerow");
let tableRowsArray = Array.from(tableRows);
tableRowsArray.map(function (row) {
  let tableCells = row.innerHTML.split("</td>");
  console.log(row.isconnected);                           // 此处返回true
  chrome.runtime.sendMessage(/*{some data}*/).then((response) => {
    let fetcheda = response.a;
    tableCells.splice(12, 0, "<td><output>" + fetcheda + "</output></td>");
    console.log(row.isConnected);                         // 此处返回false
    row.innerHTML = tableCells.join("");
    console.log(row);                                     // 行元素已被正确修改,但页面无变化
  })
});

我怀疑row变量在.then()回调的闭包作用域里部分属性丢失,需要找到在回调内修改DOM的方法,且无法重新获取对应请求的行元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:10:32