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

Chrome扩展开发报错:Uncaught (in promise) TypeError: console.log is not a function

问题原因与解决方案

问题根源

你遇到的Uncaught (in promise) TypeError: console.log is not a function,核心原因是Chrome扩展popup窗口的特性:当调用showSaveFilePicker()触发系统文件选择弹窗时,若popup失去焦点(比如用户点击文件选择器窗口),Chrome会自动关闭popup并销毁其JavaScript上下文。等文件保存完成后,Promise回调执行时,原popup的console.log所在环境已不存在,因此抛出错误。而开头的console.log能正常执行,是因为此时popup刚打开,上下文还处于活跃状态。

解决方案:将文件写入逻辑移至后台脚本

后台脚本(Service Worker,Manifest V3)的上下文不会随popup关闭而销毁,能稳定处理异步操作的回调。具体步骤如下:

  1. 更新manifest.json
    确保配置后台脚本和必要权限:
{
  "manifest_version": 3,
  "name": "文件写入测试",
  "version": "1.0",
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["nativeFileSystem"]
}
  1. 创建background.js处理文件写入
    将异步写入逻辑移到后台,通过消息通信接收popup的调用:
async function saveFile() {
  const newHandle = await window.showSaveFilePicker();
  const writableStream = await newHandle.createWritable();
  await writableStream.write("Hello world!!!");
  await writableStream.close();
  return "Saved data in file";
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "saveFile") {
    saveFile().then(result => {
      console.log(result); // 日志会输出在扩展后台控制台
      sendResponse(result);
    });
    return true; // 标记为异步响应
  }
});
  1. 修改popup.js,通过消息调用后台逻辑
console.log("Testing file write");

function onClick() {
  chrome.runtime.sendMessage({ action: "saveFile" }, (response) => {
    // 若popup未关闭,可在此接收后台返回结果并输出
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError);
    } else {
      console.log(response);
    }
  });
}

document.getElementById("testbutton").addEventListener("click", onClick);

查看后台日志

打开扩展管理页面,点击你的扩展的“服务工作者”或“查看日志”,就能看到后台脚本输出的日志内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:05:23