How can I prevent Google Colab from disconnecting?

As of March 2021, none of these methods will work as Google added a CAPTCHA button that randomly pops up after some time.

Prior to that, the solution was very easy, and didn’t need any JavaScript. Just create a new cell at the bottom having the following line:

while True:pass

Now keep the cell in the run sequence so that the infinite loop won’t stop and thus keep your session alive.

Old method:

Set a JavaScript interval to click on the connect button every 60 seconds.

Open developer-settings (in your web-browser) with Ctrl+Shift+I then click on console tab and type this on the console prompt. (for mac press Option+Command+I)

function ConnectButton(){
  console.log("Connect pushed");
  document.querySelector("#top-toolbar > colab-connectbutton").shadowRoot.querySelector("#connect").click()
}
setInterval(ConnectButton,60000);

Leave a Comment