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

输入错误邮编时Chrome/Edge可清除Local Storage但Firefox失效问题求助

Firefox下输入错误邮编触发API异常时Local Storage未被清除问题

我当前遇到的问题是:当用户在URL中输入错误邮编触发错误时,需要被清除的Local Storage数据仍被持久化,该逻辑在Chrome和Edge中运行符合预期,仅在Firefox下出现异常。

变量定义说明

  • 初始值为false的全局变量apiFailed
  • weatherData是对象数组,用于存储和访问API数据属性
  • storedData用于调用localStorage的getItem()、setItem()、removeItem()方法
  • savedWeatherData会被赋值为storedData,用于展示和读取Local Storage持久化的数据

首次加载逻辑

首次运行时localStorage无数据为null,我对此做了校验后给savedWeatherData赋值持久化数据,同时校验apiFailed为false,还通过代码刷新页面确保数据被成功读取,对应代码如下:

if (savedWeatherData == null || savedWeatherData == undefined 
|| savedWeatherData === null || savedWeatherData === undefined) {
        if (apiFailed == false) {
          console.log('savedWeatherData is NuLL');
          storedData = JSON.parse(window.localStorage.getItem('data'));
          savedWeatherData = storedData;
          window.location.reload();

          if (navigator.userAgent.indexOf("Firefox") != -1) {
            console.log('You are in Firefox');
          }
        }
      } else {
        if (apiFailed == false) {
          console.log('savedWeatherData is NOT NULL');
          // if (navigator.userAgent.indexOf("Firefox") != -1) {
        }
      }

这段逻辑在Chrome、Edge、Firefox中都运行正常,页面首次启动时无Local Storage数据,完成赋值后页面刷新,刷新后Local Storage不再为null并被赋值给savedWeatherData,后续整个应用都使用该变量读取、展示数据。

错误触发逻辑

如果用户任意时候输入错误邮编,比如误输入特殊字符,Chrome和Edge会按预期运行下方代码,展示错误页且不获取新数据:

console.log('APIFAILED status ' + apiFailed);
  if (apiFailed == true) {
    storedData = window.localStorage.removeItem("data");
    savedWeatherData = storedData;
  }

Firefox异常表现

Firefox下控制台打印的apiFailed仍为false,因此Local Storage不会被清除,Firefox不会展示错误页,不像Chrome和Edge那样展示错误提示;因为Local Storage还留存旧数据,即使用户输入了错误邮编也会展示旧数据,仿佛用户输入的是正确邮编。Firefox的Local Storage中持久化的数据未被清除,而Chrome和Edge的Local Storage数据在开发者控制台中可看到被正常清除。

错误页实现逻辑

我的错误页是通过Phaser 3 Framework实现的,对应代码如下:

if (apiFailed == true) {
    background = this.add.image(this.game.canvas.width / 2, this.game.canvas.height / 2, "sorryBackground");
    var apiFailText = this.add.text(150, this.game.canvas.height / 2 - 100, "Sorry. The weather forecast is currently unavailable",
      { fontFamily: "Open Sans, sans-serif", fontSize: 70, }).setOrigin(0, 0);
    storedData = window.localStorage.removeItem("data");
    savedWeatherData = storedData;
  }

apiFailed赋值逻辑

apiFailed是在fetch请求获取并设置API数据的catch回调中被设为true的,对应代码如下:

.catch(() => {
      console.log(".catch() called. Error within the .fetch()");
      apiFailed = true;
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:27:02