Disable Obsidian's handling of Android's back button and have it close the tab if there's no more notes in the current tab's history

Why?

On Android Firefox, if you are at the beginning of a tab’s history, the Android system back button closes that tab. On Obsidian, the back button closes the entire app if you can’t go back anymore in a tab’s history.

Some relevant feature requests:

Using the CodeScript ToolKit plugin for this

Save this as a .js file and point CodeScript Toolkit to it as your “Startup script path.” It’ll make the back button go back if a tab has history, but close the tab if not.

Version that uses removeAllListeners()

WARNING

This completely disables Obsidian’s regular response to the Android back button. So, no backing out if settings or the quick switcher with the back button. It also disables Obsidian’s URI handling (obsidian://) when the app is open. URIs still work if you launch them with Obsidian fully closed, but as soon as this startup script runs it nukes all listeners.

I think there are other listeners Obsidian uses that also get removed with this method[1]Honestly, it probably breaks more than most people are comfortable with. If anyone knows, I’d like to have a better alternative than using .removeAllListeners().

const capacitorapp = window.Capacitor?.Plugins?.App;  
  
export async function invoke(app) {  
	if (capacitorapp && capacitorapp.addListener) {  
		capacitorapp.removeAllListeners();  
		capacitorapp.addListener('backButton', () => {  
			let thisLeaf = app.workspace?.activeLeaf;  
			if (!thisLeaf) return;  
			let backHistory = thisLeaf.history.backHistory;  
			if(backHistory.length > 0) {  
				thisLeaf.history.back();  
			} else {  
				thisLeaf.detach();  
			}  
		});  
	}  
}

Version that uses setTimeout

This one checks if the layout was changed recently; if it wasn’t and there is no notes in the back history, then it closes the tab

Since it doesn’t use removeAllListeners(), Obsidian can still close if you press the back button twice in a note with no back history. It’s also pretty prone to race conditions.

const capacitorapp = window.Capacitor?.Plugins?.App;
let lastLayoutChange = new Date(Date.now() - 250);

export async function invoke(app) {
	if (capacitorapp && capacitorapp.addListener) {
		capacitorapp.addListener('backButton', () => {
			setTimeout(() => {
				let thisLeaf = app.workspace?.activeLeaf;
				if (!thisLeaf) return;
				let backHistory = thisLeaf.history.backHistory;
				if(!backHistory.length) {
					var now = new Date();
					var sinceLayoutToNow = (now.getTime() - lastLayoutChange.getTime());
					if (sinceLayoutToNow > 150) thisLeaf.detach();
				}
			}, 100);
		});

		app.workspace.on('layout-change', () => {
			lastLayoutChange = new Date();
		});
	}
}

Conclusion

I tried and failed, I think.


  1. Like the listener for when you share something to Obsidian and the listeners for when Obsidian is focused/minimized… ↩︎

1 Like