Electronでalert()を使うとUIがブロックされてしまう?

electron1

 

Alertを使用する際にカーソルが動かなくなる問題は、Electronアプリケーションでよく発生する問題らしい。これは、アプリケーションのメインプロセスとレンダラープロセスの間の非同期な通信のため、レンダラープロセスがブロックされてしまうことが原因のよう。

 

いろいろと試してみたが、Alertを使っての回避は難しそうで、モーダルウィンドウを使用して回避するしかなさそう。

 

HTML

<div id="modal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p id="modalMessage"></p>
  </div>
</div>

 

CSS

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 0 10px 10px 10px;
  border: 1px solid #888;
  width: 40%;
  border-radius:5px;
}

.close {
  color: #aaa;
  float: right;
  font-size: 24px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

 

Javascript(モーダルウィンドウの表示/非表示する関数)

const modal = document.getElementById('modal');
const modalMessage = document.getElementById('modalMessage');
const closeModal = document.getElementsByClassName('close')[0];

function showModal(message) {
  modalMessage.textContent = message;
  modal.style.display = 'block';
}

function hideModal() {
  modal.style.display = 'none';
}

closeModal.onclick = hideModal;
window.onclick = function(event) {
  if (event.target == modal) {
    hideModal();
  }
}

 

Javascript(alert()関数の代わりにshowModal()関数を使用)

if (result.success) {
  showModal('ファイルの書き込みが成功しました');
} else {
  showModal('ファイルの書き込みに失敗しました: ' + result.message);
}