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

Firebase signInWithEmailAndPassword在iOS Safari中无法正常使用的问题

iOS Safari下Firebase登录报auth/network-request-failed错误的解决办法

问题现象

调用signInWithEmailAndPassword(email, password)实现登录时,Chrome浏览器完全正常,但iOS Safari使用相同凭证登录同一网站时触发以下错误:

code: "auth/network-request-failed", message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred.

问题根源

从提供的代码来看,主要有两个核心问题:

  1. 重复初始化Firebase App:每次表单提交都执行firebase.initializeApp(config),重复初始化会导致资源冲突,在Safari环境下更容易引发网络请求异常。
  2. 未阻止表单默认提交行为:HTML表单默认会在提交时刷新页面,这会中断Firebase的异步登录请求,直接导致网络请求失败。

修正方案

1. 全局初始化Firebase App

将Firebase初始化代码移到全局作用域,确保页面加载时仅执行一次:

// 页面加载时执行一次,放在全局作用域
var config = {
  // 你的Firebase配置信息
};
firebase.initializeApp(config);

// 全局监听用户Auth状态变化,无需每次提交表单都绑定
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    console.log("firebase user is: " + user.uid); 
  } else {
    console.log("No user")
  }
});

2. 修改表单提交函数,阻止默认行为

在formSubmit函数开头添加阻止页面刷新的代码,确保异步请求能正常完成:

function formSubmit(event) {
  // 阻止表单默认提交行为,避免页面刷新中断请求
  event.preventDefault();

  var email = document.getElementById("emailInput").value;
  var password = document.getElementById("passwordInput").value;

  firebase.auth().signInWithEmailAndPassword(email, password)
  .then(function(userReturn) {
    console.log("userReturn is " + userReturn.uid);
  })
  .catch(function(error) {
    console.error(error);
  });
}

额外检查项

如果修正后仍有问题,检查iOS Safari的隐私设置:

  • 进入Safari设置 > 隐私与安全性,确保未开启“阻止所有Cookie”
  • 确认网站未被限制跨域请求权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:31:00