Skip to content

Home

Set Up a Django Server with Apache Virtual Host and Python Virtual Environment

Hello and welcome back to another episode of Continuous Improvement, the podcast where we explore tips, tricks, and strategies to help you improve your skills and workflows. I'm your host, Victor, and today we're going to dive into a step-by-step guide on setting up a Django application for production.

But before we begin, a quick reminder to subscribe to our podcast and follow us on social media to stay updated with the latest episodes. Alright, let's jump right in!

Setting up a Django application for production can be a bit daunting, but don't worry, I've got you covered. I've broken down the process into simple steps to make it easier for you to follow along. So let's get started.

Step one, assuming you already have your CentOS or Ubuntu instance running and Python installed, create a folder for your project and set the appropriate permissions. You can do this by running the following commands:

sudo mkdir /opt/yourpath/projects
sudo chown $USER /opt/yourpath/projects

Step two, if you haven't already initialized your project, you can do so by installing Django and starting your project with the following command:

python -m pip install Django
django-admin startproject APPNAME /opt/yourpath/projects/APPNAME

Remember to replace 'APPNAME' with your desired project name.

Moving on to step three, by default, the Django development server runs on port 8000. You can start the server with the command:

python manage.py runserver

Great! Now that we have our project set up, let's prepare it for production. Step four involves editing the 'settings.py' file with a few configurations. Set 'DEBUG' to False, 'ALLOWED_HOSTS' to ['*'], 'STATIC_URL' to '/static/' and 'STATIC_ROOT' to the appropriate directory path.

After making these changes, it's time for step five. We need to collect and build the static files of our Django project. Run the following command in your project's directory:

python manage.py collectstatic --noinput

The next step, step six, is to serve your web application via the Apache web server. Assuming you have Apache2 installed, enable virtual hosts for your project and create a virtual host configuration file. You can create the file by running:

touch /opt/yourpath/apache2/conf/vhosts/project-vhost.conf

In this file, you'll need to specify the WSGIDaemonProcess for your Django application. Make sure to replace all instances of 'APPNAME' with your actual project name.

To enable HTTPS, you can create another virtual host configuration file with a similar content structure. Use the command:

touch /opt/yourpath/apache2/conf/vhosts/project-https-vhost.conf

Now that we've updated the configurations, it's time for step seven - restarting the Apache server. This will allow your Django site to become operational.

Lastly, in step eight, we'll isolate Python dependencies within a virtual environment to avoid any version conflicts or dependency issues. Inside your project directory, run the following commands:

pip install virtualenv
virtualenv venv
source venv/bin/activate

This creates a folder named 'venv' that contains all your Python executables. Any subsequent 'pip install' commands will affect only this folder.

Once you've activated the virtual environment, go back and edit 'project-vhost.conf' and 'project-https-vhost.conf'. Update the 'python-home' path in both files to point to the 'venv' folder, like this:

WSGIDaemonProcess APPNAME python-home=/opt/yourpath/projects/APPNAME/venv python-path=/opt/yourpath/projects/APPNAME

Make sure to replace 'APPNAME' with your project name.

And that's it! You've successfully set up your Django application for production. Now, all that's left is to navigate to your public IP address and you should see your Django page up and running.

If you encounter any issues along the way, remember to check the Apache server error log for troubleshooting. You can do this by running:

tail /opt/yourpath/apache2/logs/error_log

That wraps up today's episode on setting up a Django application for production. I hope you found this guide helpful and that it saves you time and effort in the future.

Remember, continuous improvement is all about learning, growing, and finding better ways to do things. If you have any questions or topics you'd like me to cover in future episodes, feel free to reach out to me on social media. Thank you for tuning in to Continuous Improvement, and until next time, keep improving!

使用Apache虛擬主機和Python虛擬環境設置Django服務器

花了我一些時間才使所有東西都能一起工作,所以我想把步驟記錄下來,以節省你未來的時間。

首先,假設你已經有你的CentOS/Ubuntu實例正在運行,並且已安裝Python。創建一個專案資料夾並設定適當的權限:

    sudo mkdir /opt/yourpath/projects
    sudo chown $USER /opt/yourpath/projects

如果你還沒有初始化你的專案,你可以這樣做:

    python -m pip install Django
    django-admin startproject APPNAME /opt/yourpath/projects/APPNAME

默認情況下,服務器運行在8000端口:

    python manage.py runserver

為了準備你的Django服務器進入生產模式,編輯settings.py文件,使用以下設置:

    DEBUG = False
    ALLOWED_HOSTS = ['*']
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

然後,你可以使用下面的命令構建靜態文件:

    python manage.py collectstatic --noinput

接下來,通過Apache網絡服務器來提供你的web應用程式。假設你透過yum或apt-get安裝了Apache2,為你的專案啟用虛擬主機,並創建以下文件:

    touch /opt/yourpath/apache2/conf/vhosts/project-vhost.conf

在下面填入内容:

    <IfDefine !IS_APPNAME_LOADED>
      Define IS_APPNAME_LOADED
      WSGIDaemonProcess APPNAME python-home=/opt/yourpath/python python-path=/opt/yourpath/projects/APPNAME
    </IfDefine>
    <VirtualHost 127.0.0.1:80 _default_:80>
    ...

記住要用你的Django專案名稱替換所有的APPNAME。然後,為HTTPS創建另一個文件:

    touch /opt/yourpath/apache2/conf/vhosts/project-https-vhost.conf

並用相似的內容填充它,適當替換APPNAME。

更新配置後,重新啟動Apache服務器。你的Django站點現在應該已經可以運行了。

最後,在虛擬環境內隔離Python依賴,以避免依賴問題和版本衝突。在你的專案目錄裡,運行:

    pip install virtualenv
    virtualenv venv
    source venv/bin/activate

這會創建一個包含所有Python可執行文件的資料夾。後續的pip install命令只會影響這個資料夾。現在,回去編輯project-vhost.confproject-https-vhost.conf,將 python-home路徑改為指向venv資料夾:

由:

    WSGIDaemonProcess APPNAME python-home=/opt/yourpath/python python-path=/opt/yourpath/projects/APPNAME

變為:

    WSGIDaemonProcess APPNAME python-home=/opt/yourpath/projects/APPNAME/venv python-path=/opt/yourpath/projects/APPNAME

一定要將Python home路徑指向venv資料夾,而不是/bin可執行檔或Python位置,以避免出現500錯誤。如果你遇到問題,請檢查Apache服務器的錯誤日誌:

    tail /opt/yourpath/apache2/logs/error_log

就這樣!在你的公開IP地址上導航,你應該能看到你的Django頁面。

附註:如果你在WSGI層面遇到超時錯誤:

    Timeout when reading response headers from daemon process

編輯project-vhost.confproject-https-vhost.conf,在WSGIDaemonProcess下面添加以下行:

    WSGIApplicationGroup %{GLOBAL}

這種增加可以解決由Python C擴展模組(如NumPy)導致的超時。

Stop Downloading Apps for Everything

Apps are becoming increasingly irrelevant. There's no need to download ineffective software when browsers can serve as adequate substitutes. The primary benefit of using apps is data gathering and ad serving, which favor tech giants rather than end-users.

A competent programmer invests time in refining their work. They construct test cases, simplify complex problems into smaller tasks, and think deeply about the subject at hand. In contrast, less skilled developers often lack the will or talent to achieve anything significant. As a user, it's difficult to determine which app is superior.

When a developer makes an error, the repercussions are usually minor. At worst, they might receive a poor rating on the app store. In more severe cases, management may hold them accountable. However, for the most part, there are no lasting consequences. Some developers may patch the flaws, while others may introduce new ones. You won't know unless you run comprehensive regression tests.

The problem isn't solely with poor developers; even talented ones find themselves trapped in an increasingly irrational industry. These skilled programmers often lack the time to specify requirements or plan thoroughly. Furthermore, they're under immense pressure to churn out new features constantly, especially since the release of the latest iPhone. Many companies expect their developers to produce multiple new features daily to boost app downloads, a pace that's unsustainable for maintaining quality.

Creating well-tested, robust software that handles all possible states is a challenge in itself. This is made even more difficult by constant interruptions from Slack messages and progress report meetings. Often, companies hire experienced full-stack engineers to complete the work, only to find that it's prohibitively expensive.

Users are largely unaware of these challenges. Burdened by spaghetti code and countless defects, software developers become disenchanted, cynical, or both. It's no wonder that many transition to project management roles, which offer less stress, higher income, and more predictable hours. They no longer aim to transform the world through better software.

The blame for this dysfunctional software engineering culture doesn't solely rest on the companies. Tech behemoths like Apple, Google, Facebook, and Amazon have shaped the way we do business. As we spend more time on their platforms, they grow more successful, encouraging a race to the bottom in terms of software quality. My advice, especially to my fellow software developers, is to opt out of this race. True professionals should pride themselves on their carefully crafted work, rather than behaving like code monkeys.

Stop Downloading Apps for Everything

Hello and welcome to "Continuous Improvement," the podcast where we explore ways to improve ourselves and the world around us. I'm your host, Victor, and in today's episode, we'll be diving into a topic that affects both developers and users alike - the growing irrelevance of mobile apps.

It's no secret that apps have become an integral part of our lives. We rely on them for various tasks, from ordering food to tracking our workouts. But have you ever stopped to think about the effectiveness of those apps?

According to a recent blog post I came across, apps are becoming increasingly irrelevant. Why download and clutter your device with ineffective software when your browser can serve as an adequate substitute? It seems the primary benefit of using apps lies in data gathering and ad serving, which favor tech giants rather than us, the end-users.

As a user, it's difficult to determine which app is superior and genuinely offers value. The post suggests that the competency of the programmer behind an app plays a significant role in its effectiveness. Skilled programmers invest time in refining their work - constructing test cases, simplifying complex problems, and thinking deeply about the subject at hand.

On the other hand, less skilled developers may lack the necessary will or talent to achieve anything significant. This leads to a sea of apps where quality is questionable at best.

So, what happens when a developer makes an error? Well, the repercussions are often minor. At worst, they might receive a poor rating on the app store, but for the most part, there are no lasting consequences. Some developers might patch the flaws, while others may introduce new ones. It's a constant cycle of trial and error, leaving us, the users, with unreliable software and little control over its quality.

But the problem doesn't solely lie with poor developers. Even talented programmers find themselves trapped in an increasingly irrational industry. They lack the time to specify requirements or plan thoroughly, and are under immense pressure to churn out new features constantly. All this to keep up with the industry's demand for constant innovation.

Creating robust, well-tested software that handles all possible states is a challenge in itself. And to top it off, developers have to deal with constant interruptions, like Slack messages and progress report meetings, which only add to their struggles. Companies often hire experienced full-stack engineers to complete the work, only to find that it's prohibitively expensive.

Users, on the other hand, are largely unaware of these challenges. They simply want reliable and efficient apps, but are often burdened with spaghetti code and countless defects. It's no wonder that many talented developers transition to project management roles, seeking less stress, higher income, and more predictable hours. The ambition to transform the world through better software wanes.

But who can we blame for this dysfunctional software engineering culture? The post argues that tech behemoths like Apple, Google, Facebook, and Amazon have shaped the industry with their platforms and policies. As we spend more time on their platforms, they become more successful, further encouraging a race to the bottom in terms of software quality.

So, what's the solution? The author advises software developers, like myself and many of you listening, to opt out of this race. True professionals should take pride in their carefully crafted work and refuse to be treated like mere code monkeys.

And that brings us to the end of today's episode of "Continuous Improvement." I hope you found this discussion thought-provoking, whether you're a developer or a user of mobile apps.

Remember, the power for change lies in the hands of those who care about the quality of software we use every day. Let's strive for better, more reliable apps that truly serve us.

Join me next time as we delve into another topic of continuous improvement. Until then, take care and keep striving for excellence.

不要為所有事情下載應用程式

應用程式越來越無關緊要。 當瀏覽器可以作為足夠的替代品時,就不需要下載無效的軟件。 使用應用程式的主要好處是數據收集和廣告服務,這有利於科技巨頭而不是終端用戶。

一個能幹的程序員會花時間淬煉他們的工作。他們構建測試案例,將複雜的問題簡化為較小的任務,並對手頭的主題進行深思熟慮。相比之下,技能較差的開發人員往往缺乏實現任何重大成就的意願或才能。作為用戶,很難確定哪個應用程式更優越。

當開發人員犯錯時,後果通常是次要的。最壞的情況下,他們可能會在應用商店上獲得差評。在更嚴重的情況下,管理層可能會追究他們的責任。但是,大多數情況下,沒有持久的後果。有些開發人員可能會修補這些缺陷,而其他人可能會引入新的缺陷。您不進行全面的回歸測試就無法知道。

問題不僅僅在於差劣的開發者;即使是有才華的人也發現自己陷入了一個日益非理性的行業。這些技能優秀的程序員往往沒有時間來明確要求或進行 gronding 的計劃。此外,他們承受著不斷推出新功能的巨大壓力,特別是自從最新的 iPhone 發布以來。許多公司希望他們的開發人員能每天產出多個新功能以增加應用程式的下載量,但這種節奏對於保持質量來說是無法持續的。

創建經過充分測試,堅固的軟件以處理所有可能的狀態本身就是一項挑戰。這更加困難,因為來自 Slack 消息和進度報告會議的持續干擾。通常,公司會雇用經驗豐富的全棧工程師來完成工作,卻發現這成本過高。

用戶大多並未意識到這些挑戰。受到 spaghetti 代碼和無數缺陷的困擾,軟件開發人員變得不滿或悲觀,甚至兩者兼而有之。難怪許多人轉行成為項目管理角色,這提供了較少的壓力,更高的收入和更可預見的工作時間。他們不再致力於通過更好的軟件改變世界。

這種失功能的軟件工程文化的責任並不完全在於公司。像 Apple、Google、Facebook 和 Amazon 這樣的科技巨頭塑造了我們做生意的方式。當我們在他們的平台上花費更多的時間,他們就會變得更成功,從而鼓勵了軟件質量的低劣競爭。我特別建議我的軟件開發同行退出這場競賽。真正的專業人士應該以他們精心打造的工作為傲,而不是表現得像寫代碼的猴子。

Install Ubuntu 20.04 LTS on MacBook Pro 14,1

Ubuntu 20.04 has just been released, and I couldn't wait to try it out and install it on my MacBook Pro 14.1 model. In this post, I will detail what works, what doesn't, and how to work around those issues.

The installation steps are simple:

  1. Download a copy of the Ubuntu 20.04 ISO image from https://ubuntu.com/download/desktop.
  2. Obtain a USB drive and format it to FAT via macOS Disk Utility.
  3. Use Etcher to create a bootable USB drive. You can download the software here.
  4. After flashing the drive with the ISO image, reboot your Mac and press the Option key to select booting from the USB drive.

Once you start booting from the USB drive, you'll notice that the trackpad doesn't work. However, you can either use an external mouse or continue the installation via keyboard. (You can fix the driver issue later, as outlined below.) Follow the on-screen instructions, and you should be able to boot into the Ubuntu operating system. One thing I appreciate about this version is that the boot screen is black instead of the purple seen in previous versions.

Out of the box, the following features work:

  • Keyboard with backlight
  • Screen display and graphics card
  • WiFi connectivity
  • USB ports
  • Battery

Here's what doesn't work by default:

  • Speakers (workaround: use external headphones or HDMI on an external monitor, or fix with this driver)
  • Trackpad (workaround: use an external mouse or install the driver here)
  • Bluetooth (can be fixed by installing this driver; note that if you encounter a 404 error while trying to download version 5.4.0, editing the script to use version 5.4.1 should work)
  • Camera (can be fixed by installing this driver)

If you encounter an error while installing the camera driver, you can resolve it by modifying your Makefile:

Change:

    install:
      $(MAKE) -C $(KDIR) M=$(PWD) modules_install

to

    install:
      cp facetimehd.ko /lib/modules/$(shell uname -r)/extra; depmod -a

Additional customizations I recommend after installation include:

  • Switching to dark mode.
  • Displaying battery percentage by running:
  gsettings set org.gnome.desktop.interface show-battery-percentage true
  • Installing GNOME Tweaks.
  • Installing Ubuntu restricted extras:
  sudo apt install ubuntu-restricted-extras
  • Installing the Atom editor:
  wget -qO - [https://packagecloud.io/AtomEditor/atom/gpgkey](https://packagecloud.io/AtomEditor/atom/gpgkey) | sudo apt-key add -
  sudo sh -c 'echo "deb [arch=amd64] [https://packagecloud.io/AtomEditor/atom/any/](https://packagecloud.io/AtomEditor/atom/any/) any main" > /etc/apt/sources.list.d/atom.list'
  sudo apt-get update
  sudo apt-get install atom
  • Disabling the trackpad while typing:
  gsettings set org.gnome.desktop.peripherals.touchpad disable-while-typing true

With these steps, you should now have a secure and high-performance operating system. Though the journey with Linux can be challenging, it's rewarding because of the customization options and the learning experiences it offers. Proceed with caution, though: while you can create all sorts of customizations, you can also crash your system if you don't know what you're doing. If you have any questions or comments, feel free to get in touch.

Install Ubuntu 20.04 LTS on MacBook Pro 14,1

Hello and welcome to "Continuous Improvement," the podcast that helps you embrace change and optimize your life. I'm your host, Victor, and in today's episode, we'll be discussing Ubuntu 20.04 and how to install it on a MacBook Pro 14.1 model.

Ubuntu 20.04 has just been released, and I couldn't wait to give it a try. In this episode, I'll be sharing what works, what doesn't, and how to work around those issues. So, let's dive in!

To begin, you'll want to download a copy of the Ubuntu 20.04 ISO image from ubuntu.com. Once you have the image, use Etcher to create a bootable USB drive. Don't worry, I'll include the download links in the show notes.

Now, when you start booting from the USB drive, you might notice that the trackpad doesn't work. But don't worry, there's a workaround. You can either use an external mouse or continue the installation via keyboard. We'll fix the driver issue later.

Once you're in the Ubuntu operating system, you'll find that the keyboard with backlight, screen display and graphics card, WiFi connectivity, USB ports, and battery all work out of the box. That's great!

But, there are a few things that don't work by default. Let's go through them and their workarounds:

  • Speakers: To fix this, you can use external headphones or HDMI on an external monitor. If you prefer fixing it with a driver, you can find the instructions and the driver in the show notes.

  • Trackpad: As mentioned earlier, you can use an external mouse during installation. But if you want to use the trackpad, you can install the driver by following the link provided.

  • Bluetooth: If you're facing Bluetooth issues, don't worry. There's a driver available that will solve the problem. Just follow the instructions in the show notes.

  • Camera: Another issue you might face is with the camera. But fret not, there's a driver available to fix it. You can find all the details in the show notes as well.

Once you've resolved these issues, you can make additional customizations to enhance your Ubuntu experience. For example, switching to dark mode, displaying battery percentage, installing GNOME Tweaks, Ubuntu restricted extras, and the Atom editor. Again, the instructions for these customizations will be in the show notes.

One final tip I have for you is to disable the trackpad while typing. This can greatly improve your typing experience. You'll find the command to do so in the show notes.

Remember, while Ubuntu offers endless customization options, it's essential to proceed with caution. Enthusiasm can sometimes lead to crashing your system if you're not careful. If you have any questions or need help, feel free to reach out to me. I'm here to assist you on your Ubuntu journey.

That's it for today's episode of "Continuous Improvement." I hope you found this information helpful. Embrace change, optimize your life, and keep striving for continuous improvement. I'm Victor, your host, signing off. See you next time!

在 MacBook Pro 14,1 上安裝 Ubuntu 20.04 LTS

Ubuntu 20.04 剛剛問世,我迫不及待想要在我的 MacBook Pro 14.1 模型上試用並安裝它。在這篇文章中,我將詳述哪些東西能運作、哪些不能,以及如何解決這些問題。

安裝步驟很簡單:

  1. https://ubuntu.com/download/desktop 下載 Ubuntu 20.04 ISO 映像檔。
  2. 獲取一個 USB 隨身碟並透過 macOS 磁片工具將其格式化為 FAT。
  3. 使用 Etcher 建立可啟動的 USB 隨身碟。你可以在 這裡 下載該軟體。
  4. 在將 ISO 映像檔燒錄到 USB 隨身碟之後,重啟你的 Mac 並按 Option 鍵以選擇從 USB 碟機開機。

一旦你開始從 USB 隨身碟開機,你會注意到觸控板不起作用。然而,你可以使用外接滑鼠或繼續用鍵盤進行安裝。 (如下所述,稍後可以修復驅動程式問題。) 按照屏幕上的指示操作,你應該可以順利開啟 Ubuntu 操作系統。我對這個版本很欣賞的一點是,開機畫面是黑色的,而不是在以前的版本中看到的紫色。

以下特性開箱即用:

  • 有背光的鍵盤
  • 螢幕顯示和顯示卡
  • WiFi 連線
  • USB 插口
  • 電池

以下是預設不能運作的:

  • 揚聲器 (解決方法:使用外接耳機或透過外部監視器上的 HDMI,或者使用這個驅動程式修復)
  • 觸控板 (解決方法:使用外接滑鼠或安裝這裡的驅動程式)
  • 藍牙 (可以透過安裝這個驅動程式修復。請注意,如果在嘗試下載 5.4.0 版本時遇到 404 錯誤,修改腳本以使用 5.4.1 版本應該可以解決問題)
  • 攝像頭 (可以透過安裝這個驅動程式修復)

如果在安裝攝像頭驅動程式時遇到錯誤,你可以通過修改你的 Makefile 解決:

選擇:

    install:
      $(MAKE) -C $(KDIR) M=$(PWD) modules_install

更改為

    install:
      cp facetimehd.ko /lib/modules/$(shell uname -r)/extra; depmod -a

我推薦的安裝後的其他自定義操作包括:

  • 切換到深色模式。
  • 顯示電池百分比,運行:
  gsettings set org.gnome.desktop.interface show-battery-percentage true
  • 安裝 GNOME Tweaks。
  • 安裝 Ubuntu restricted extras:
  sudo apt install ubuntu-restricted-extras
  • 安裝 Atom 編輯器:
  wget -qO - [https://packagecloud.io/AtomEditor/atom/gpgkey](https://packagecloud.io/AtomEditor/atom/gpgkey) | sudo apt-key add -
  sudo sh -c 'echo "deb [arch=amd64] [https://packagecloud.io/AtomEditor/atom/any/](https://packagecloud.io/AtomEditor/atom/any/) any main" > /etc/apt/sources.list.d/atom.list'
  sudo apt-get update
  sudo apt-get install atom
  • 在鍵盤輸入時禁用觸控板:
  gsettings set org.gnome.desktop.peripherals.touchpad disable-while-typing true

有了這些步驟,你現在應該擁有一個安全且高效能的操作系統。雖然 Linux 的旅程可能充滿挑戰,但由於它提供的自定義選項和學習經驗,使得這個旅程變得非常有價值。不過要謹慎行事:雖然你可以創建各種自定義選項,但如果你不知道自己在做什麼,也可能會導致你的系統崩潰。如果你有任何問題或意見,歡迎隨時與我聯繫。

Handling Browser Close Events with JavaScript

In certain scenarios, you may not want users to close their browser and exit the session. For instance, if a user is in the middle of filling out a form without saving, or in the midst of a payment transaction that hasn't been completed, you could prompt the user with a confirmation dialog when they attempt to close the browser.

Here's what the dialog looks like in Chrome:

And in Firefox:

This functionality can be implemented by using the beforeunload event in JavaScript. Add the following code to your web page:

window.addEventListener("beforeunload", event => {
  // Cancel the event as specified by the standard.
  event.preventDefault()
  // Chrome requires returnValue to be set.
  event.returnValue = ""
})

Note that this event will only trigger if the user has had some interaction with the page. Otherwise, it won't activate. Additionally, the event will be triggered in the following three scenarios:

  1. The user clicks to close the browser.
  2. The user clicks to refresh the page.
  3. The user clicks the back button.

If you want to remove this confirmation dialog, perhaps after the user has saved the form or completed the payment transaction, you can do so like this:

window.removeEventListener("beforeunload", callback)

Since the primary purpose of this dialog is to remind users to save their changes before leaving, there is no additional event listener to capture the result of the exit dialog. In other words, you can't determine whether the user chose to leave or stay on the page.

For more information, you can consult the latest MDN Web Docs here: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

Handling Browser Close Events with JavaScript

Welcome back to another episode of "Continuous Improvement". I'm your host, Victor, and today we'll be discussing an important aspect of user experience on the web - preventing accidental page exits. Have you ever been in a situation where you were filling out a form or making a payment, and accidentally closed your browser, losing all your progress? Well, we have a solution for you.

In this episode, we'll dive deep into the implementation of a confirmation dialog using the beforeunload event in JavaScript. This will help you prompt users with a warning before they close their browsers, ensuring they are aware of their unsaved changes. So, let's get started!

[BACKGROUND FADES]

First, let's take a look at what the confirmation dialog actually looks like. In different browsers, it can vary slightly in appearance. In Chrome, for example, it may look like this. [DESCRIBING CHROME DIALOG]

And in Firefox, it may appear slightly different. [DESCRIBING FIREFOX DIALOG]

[BACKGROUND FADES]

So, how can you implement this dialog on your web page? It's actually quite simple. Just add the following code to your JavaScript file:

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as specified by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

By adding this event listener, you're informing the browser to trigger the confirmation dialog when the user attempts to close the browser, refresh the page, or click the back button. The event.preventDefault() cancels the event, ensuring the dialog is shown, and the event.returnValue = '' satisfies Chrome's requirements.

[BACKGROUND FADES]

It's important to note that the beforeunload event will only trigger if the user has interacted with the page in some way. If they haven't, the event won't activate. Once you've implemented this functionality, the confirmation dialog will keep users from inadvertently leaving the page without saving their changes or completing their transaction.

[BACKGROUND FADES]

But what if you want to remove the confirmation dialog at some point? Maybe after the user has saved the form or completed the payment. Well, you can easily do that too. Just use the following code:

window.removeEventListener('beforeunload', callback);

This line of code will remove the event listener, so the confirmation dialog no longer appears when attempting to leave the page. However, remember to replace callback with the actual function or arrow function you used in the addEventListener method.

[BACKGROUND FADES]

It's worth mentioning that the purpose of this confirmation dialog is to remind users to save their changes before leaving, and it doesn't provide any way to determine whether the user chose to stay or leave the page. So keep that in mind while implementing it in your project.

[BACKGROUND FADES]

And that's a wrap for today's episode of "Continuous Improvement". We hope you found this topic helpful in enhancing user experience on your website. Remember, implementing a confirmation dialog using the beforeunload event can prevent users from accidentally closing their browsers and losing their progress. For more detailed information and additional resources, you can check out the MDN Web Docs.

Thank you for listening to "Continuous Improvement". I'm Victor, your host, and I'll catch you in the next episode. Until then, happy coding!