【问题标题】:firebase realtime database not working in chromefirebase 实时数据库在 chrome 中不起作用
【发布时间】:2021-10-13 03:06:49
【问题描述】:

我已经设置了一个 firebase 实时数据库,当我运行我的代码时,它可以在 safari 中运行,但在 chrome 中却无法运行。

这是我的 index.js 文件链接到一个 html 文件为<script type="module" src="index.js"></script>

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js';
import { getDatabase, set, ref } from 'https://www.gstatic.com/firebasejs/9.1.2/firebase-database.js';

const firebaseApp = initializeApp({
    apiKey: "xxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx",
    });

const db = getDatabase(firebaseApp)

var x = document.getElementById("Identifiant");
var y = document.getElementById("Password");

function senddata(){
    set(ref(db, 'users/' + x.value), {
        username: x.value,
        password: y.value
        });
    window.location.href = 'https://www.youtube.com';
    };

var btn = document.getElementById('btnconx');
btn.addEventListener('click', senddata);

所以这在 safari 中有效,但在 chrome 中,它确实将我发送到 YouTube,但它没有写入数据库。但如果我不输入“window.location.href = 'https://www.youtube.com';”,即使在 chrome 中,它也会将数据发送到数据库。如何使其工作,以便在将数据写入数据库后,将用户发送到 YouTube(或基本上任何网站)。请注意,按钮“btn”为 type="button",并且位于带有 method="GET" 的表单内。

【问题讨论】:

    标签: javascript html firebase


    【解决方案1】:

    听起来它可能会在有机会发送您的数据之前重定向您的页面。为了解决这个问题,我建议使 senddata() 异步并等待 set()。这应该允许您的页面在重定向之前发送数据。

    ES6

    async function senddata(){
        await set(ref(db, 'users/' + x.value), {
            username: x.value,
            password: y.value
        });
        window.location.href = 'https://www.youtube.com';
    };
    

    ES5

    function senddata(){
        set(ref(db, 'users/' + x.value), {
            username: x.value,
            password: y.value
        }).then(() => {
            window.location.href = 'https://www.youtube.com';
        });
    };
    

    【讨论】:

    • 谢谢它有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2021-05-10
    • 2021-06-22
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多