jquery 如何处理同一个节点的firebase打开在多个标签使用JavaScript

ih99xse1  于 2023-06-22  发布在  jQuery
关注(0)|答案(1)|浏览(121)

我有firebase节点“formbuilder_1”,“formbuilder_2”,“formbuilder_3”等。如果节点“formbuilder_1”在一个选项卡中打开,而当用户在另一个选项卡中打开同一节点时,则警报消息显示它已在选项卡中打开。与在线Excel工作表相同的示例。我们怎么能这样做。
下面是我的代码:

$.urlParam = function (name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)')
    .exec(window.location.href);
  if (results == null) {
    return 0;
  }
  return results[1] || 0;
}
let caseId = $.urlParam('case_id');
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js";
import { getDatabase, ref, set, onValue, child, update, get, query } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-database.js";
// Your web app's Firebase configuration 
 
const firebaseConfig = {
  apiKey: "AIzaSyBQlm0cLrmY19nDXyRQRm_C_51gulT0mRY",
  authDomain: "devt-23a3b.firebaseapp.com",
  projectId: "devt-23a3b",
  storageBucket: "devt-23a3b.appspot.com",
  messagingSenderId: "949860997571",
  appId: "1:949860997571:web:d398ef26b70791de75c576"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

const formBuilderRef = ref(database, 'formbuilder');
const formSettingRef = child(formBuilderRef, 'form_setting');
const sectionsRef = child(formBuilderRef, 'sections');
const rowsRef = child(formBuilderRef, 'rows');
const formBuilderRefT = ref(database, 'formbuilder_' + caseId);
const formField = child(formBuilderRefT, 'fields');

// Create a new Broadcast Channel with a unique name
const broadcastChannel = new BroadcastChannel('firebase_channel');

$(document).ready(function () {
  // ...

  // form field setting for testing.....
  const fieldObject = { [`name`]: '' };
  checkNodeExists(formBuilderRefT, (node) => {
    console.log("_check node ", node)
    if (node) {
      onValue(formField, (snapshot) => {
        const data = snapshot.val();
        console.log("Received data:", data);
        // Update the UI or perform other actions based on the received data
        
        // Broadcast the updated data to all open tabs
        broadcastChannel.postMessage(data);
      });
    } else {
      set(formField, fieldObject);
    }
  });

  // ...

  $("body").on('keyup', '.user_input', function () {
    let defaultValue = $(this).val();
    const updateObject = { [`name`]: defaultValue };
    checkNodeExists(formBuilderRefT, (node) => {
      console.log("_check node ", node)
      set(formField, updateObject);
    });
  });

  // Listen for messages from other tabs
  broadcastChannel.onmessage = (event) => {
    const data = event.data;
    console.log("Received broadcasted data:", data);
    // Update the UI or perform other actions based on the received data
  };
});

function checkNodeExists(formBuilderRefT, callback) {
  get(formBuilderRefT)
    .then((snapshot) => {
      if (snapshot.exists()) {
        callback(true)
      } else {
        callback(false)
      }
    })
    .catch((error) => {
      callback(false)
    });
}

这是js fiddle的例子。
演示:https://jsfiddle.net/29era35f

请引导。
谢谢

aamkag61

aamkag611#

您的代码比您想象的要简单,您根本不需要使用firebase来使其工作,因此您可以简化用例,将caseId变量发送到其他选项卡。

const channel = new BroadcastChannel('firebase_channel');

const tabs = [];

let case_id = document.querySelector('#case-id');

run.addEventListener('click', () => {
    const new_case_id = case_id.value;
    if (tabs.includes(new_case_id)) {
        alert('Tab "${new_case_id}" taken');
    } else {
        channel.postMessage(new_case_id);
        alert(`Tab processing ${new_case_id}`);
    }
})

channel.onmessage = ({data}) => {
    tabs.push(data);
};
<input id="case-id"/>
<button id="run">run</button>

看起来这个代码段在StackOverflow上不起作用,可能是因为沙盒环境。但是你可以试试这个CodePen演示:https://codepen.io/jcubic/pen/PoxGmjW
如果你的代码需要从URL获取case_id。
另外请注意,要获取URL搜索参数,您可以使用以下代码而不是正则表达式:

const case_id = new URLSearchParams(location.search).get('case_id');

你不需要任何库

相关问题