swipe-back-control
Version:
Capacitor plugin to enable or disable the swipe back gesture on iOS devices for specific pages.
104 lines • 3.75 kB
JavaScript
import { App } from '@capacitor/app';
import { WebPlugin } from '@capacitor/core';
export class SwipeBackControlWeb extends WebPlugin {
constructor() {
super();
this.disabledPages = new Set();
try {
// Listen for back navigation attempts
window.addEventListener('popstate', this.handlePopState.bind(this));
// Set up back button handler using Capacitor's App plugin
this.setupBackButtonHandler();
}
catch (error) {
console.error('Failed to initialize SwipeBackControl:', error);
}
}
async setupBackButtonHandler() {
try {
// This ensures App plugin is ready and available
if (App) {
App.addListener('backButton', async () => {
try {
const { shouldBlock } = await this.shouldBlockBackButton();
if (shouldBlock) {
// If back should be blocked, do nothing - this prevents
// both back navigation and app exit
console.log('Back navigation is disabled on this page');
}
else {
// Navigate back in history
window.history.back();
console.log('Navigating to previous page');
}
}
catch (error) {
console.error('Error in back button handler:', error);
}
});
console.log('Back button handler registered');
}
}
catch (error) {
console.error('Failed to set up back button handler:', error);
}
}
async enableSwipeBack(options) {
try {
const { enabled, currentPage } = options;
if (enabled) {
this.disabledPages.delete(currentPage);
}
else {
this.disabledPages.add(currentPage);
}
// Update navigation state if needed
if (!enabled) {
history.pushState(null, document.title, location.href);
}
}
catch (error) {
console.error('Failed to enable/disable swipe back:', error);
throw error;
}
}
async disableSwipeBack() {
try {
const currentPage = window.location.pathname;
await this.enableSwipeBack({ enabled: false, currentPage });
}
catch (error) {
console.error('Failed to disable swipe back:', error);
throw error;
}
}
async shouldBlockBackButton() {
try {
const currentPage = window.location.pathname;
const shouldBlock = this.disabledPages.has(currentPage);
return { shouldBlock, currentPage };
}
catch (error) {
console.error('Failed to check if back button should be blocked:', error);
throw error;
}
}
handlePopState() {
try {
const currentPage = window.location.pathname;
if (this.disabledPages.has(currentPage)) {
// Prevent back navigation by pushing a new state
history.pushState(null, document.title, location.href);
}
}
catch (error) {
console.error('Error handling pop state:', error);
}
}
// The echo function can be used for debugging or testing purposes
async echo(options) {
console.log('ECHO', options);
return options;
}
}
//# sourceMappingURL=web.js.map