首页 > 解决方案 > 如何防止创建多个电子实例 dialog.showMessageBox

问题描述

问题是每次调用 dialog 函数时都会创建多个对话框,第一个只创建一个,第二个调用创建两个,第三个调用创建三个实例,依此类推...... '在选择一个选项后不会关闭,而是隐藏自己,并且所有的 em 在下一个对话框调用中再次显示。

用途

如果用户尝试获取外部数据但 Internet 不可用,我将使用该对话框向用户显示消息。

谢谢

const { ipcMain } = require("electron");

let isOnline = (win, once = false, pass, user_callback) => {
  //  the availability of internet flag
  let CONNECTION;

  // flags to indicate if it's the first check to not execute multiple functions
  let FIRSTCH = true;

  // flags to execute the fetching only once
  let DONE = false;

  /**
   * Show a warning to the user.
   * You can retry in the dialog until a internet connection
   * is active.
   */
  ipcMain.on("online-status-changed", (event, status) => {
    if (status === "online") {
      CONNECTION = true;

      // Verify for first time
      if (FIRSTCH) {
        if (!DONE) {
          execute();
          FIRSTCH = false;
        }
      }
    } else {
      if (!DONE) {
        FIRSTCH = false;
        CONNECTION = false;
        execute();
      }
    }
  });

  var message = function () {
    const { dialog } = require("electron");

    dialog
      .showMessageBox(win, {
        title: "There's no internet",
        message: "No internet available, do you want to try again ?",
        type: "warning",
        buttons: ["Try Again", "Enter Without Fetching Data"],
        defaultId: 0,
      })
      .then((result) => {
        if (result.response === 0) {
          // try again
          execute();
        }

        if (result.response === 1) {
          //enter without fetch
          pass();
        }
      });
  };

  var execute = function () {
    if (CONNECTION) {
      // Execute action if internet available.
      user_callback();
      if (once) DONE = true;
    } else {
      // Show warning to user
      // And "retry" to connect
      message();
    }
  };
};

module.exports = isOnline;

标签: javascriptelectrondialog

解决方案


推荐阅读