Front-end interview: Only one pop-up window can pop up in the browser a day. How to achieve it? Tell me about your thinking?

To implement the function that only one pop-up window pops up in a day in the browser, you can use local storage (localStorage) to record the status of the pop-up window. Here is one implementation:

  1. When the page loads, check if the popup state flag already exists in local storage.
  2. If the marker does not exist or the marker indicates that the last popup was on the previous day, show the popup and update the marker in local storage to the current date.
  3. If the flag exists and indicates that the last popup was on the current day, then don't show the popup.

Here is sample code:

    // 检查弹窗状态的函数
    function checkPopupStatus() {
      // 获取当前日期
      const currentDate = new Date().toDateString();

      // 从本地存储中获取弹窗状态标记
      const popupStatus = localStorage.getItem('popupStatus');

      // 如果标记不存在或者标记表示上一次弹窗是在前一天
      if (!popupStatus || popupStatus !== currentDate) {
        // 显示弹窗
        displayPopup();

        // 更新本地存储中的标记为当前日期
        localStorage.setItem('popupStatus', currentDate);
      }
    }

    // 显示弹窗的函数
    function displayPopup() {
      // 在这里编写显示弹窗的逻辑,可以是通过修改 DOM 元素显示弹窗,或者调用自定义的弹窗组件等
      console.log('弹出弹窗');
    }

    // 在页面加载时调用检查弹窗状态的函数
    checkPopupStatus();

In this implementation, checkPopupStatusthe function will be called when the page loads. It first fetches the current date and fetches the flag of the popup state from local storage. If the marker does not exist or indicates that the last pop-up window was the previous day, displayPopupthe function will be called to display the pop-up window, and the marker in local storage will be updated to the current date.

In this way, you can ensure that only one pop-up window will pop up on the same day, and the pop-up window will not be repeated on subsequent page loads.

Guess you like

Origin blog.csdn.net/m0_69429961/article/details/131514561