How do you close the localhost server using a button in React.js?

I want to create a button that closes the server on click. I have used the following way:

In App.js

import Quit from './functions/QuitFunction.js';

function App() {
   return(
     <div>
         <button onClick= {Quit} > Quit </button>
    </div>
  )
}

export default App;

In QuitFunction.js

const Quit = () => {
   window.open("", "_self");
   window.close();
}

export default Quit;

This method of opening a blank tab in the same window and closing it worked in Vanilla JS, but in React.js, it would show the error that scripts would close those they opened. This error didn’t show in plain JS, so are any more methods working?

1 Like

In React.js, you cannot close the window directly as it goes against the security policy of the browser. Instead, you can try other ways to achieve the same functionality. Here are some methods that you can try:

Method 1: Using window.open()
You can open a new blank window and close the current window using the window.open() method.

In App.js:
javascript

function App() {
   const handleQuit = () => {
       const newWindow = window.open("", "_self");
       window.close();
       newWindow.close();
   }
   
   return (
     <div>
         <button onClick={handleQuit}> Quit </button>
     </div>
   )
}

In this method, you first open a new blank window using the window.open() method with an empty URL and the _self parameter to open it in the current window. Then, you close the current window using the window.close() method. Finally, you close the new window using the newWindow.close() method.

Method 2: Using window.location.href

You can also use the window.location.href property to redirect the user to a blank page, which will close the current window.

In App.js:
javascript

function App() {
   const handleQuit = () => {
       window.location.href = "about:blank";
   }
   
   return (
     <div>
         <button onClick={handleQuit}> Quit </button>
     </div>
   )
}

In this method, you set the window.location.href property to “about:blank”, which will redirect the user to a blank page and close the current window.

Method 3: Using Electron

If you are building a desktop application using Electron, you can use the app.quit() method to quit the application.

In QuitFunction.js:
javascript

const electron = require('electron');
const { app } = electron.remote;

const Quit = () => {
   app.quit();
}

export default Quit;

In this method, you import the Electron module and use the app.quit() method to quit the application.

I hope this helps you achieve the desired functionality.

Thank you for the solution! :grinning:

1 Like

npm install kill-port --save-dev

const stopServer = () => {
const kill = require(‘kill-port’);
// Replace ‘3000’ with the port number of your server
kill(3000).then(() => console.log(‘Server stopped’));
};

Stop Server

@himanshu.arya @aditya2010.kadiyala