route-interceptor

A front-end generic route interceptor
1,866 10
Install
npm install route-interceptor
Latest Version:0.1.3
License:MIT
Last Updated:Jun 19, 2022
Links: GitHub  ·  npm
Maintainer: suchangv

Route Interceptor

Introduction

This package can intercept front-end route jumps, Does not depend on any framework, So you can use it in React, Vue, etc.

Online Demo

todo

How to use

1. Installation

  npm i route-interceptor

2. Add this code where you like

import { create } from "route-interceptor";

const interceptor = create({
  way: ["a", "window.open", "history", "hash", "location"],
  intercept: (path) => {
    return path.replace("/bbb", "/ccc");
  },
});

interceptor.start();

API

Parameter Description Type Default
way Way to be intercepted ('a' | 'window.open' | 'history' | 'hash' | 'location')[] []
intercept intercept rule callback () => string | false () => false

way

a

Intercept Anchor tag jump, if Anchor tag has click event and called preventDefault, Will not be intercepted.

window.open

Intercept window.open

history

Will intercept both history.pushState and history.replaceState

hash

Intercept hash change, such as location.hash = '#some'

location

Because the origin location object can't be override, intercept set location.href and location.replace, You need to use Babel at the same time or use global object $location to jump.

This is type declaration for $location.

interface Window {
  $location: Pick<Location, "href" | "replace">;
}

Use babel plugin.

// .babelrc.js
module.exports = {
  plugins: ["route-interceptor/plugins/babel"],
};

How it works

location.href = "https://www.google.com";
location.replace("https://www.google.com");
// will transform to
$location.href = "https://www.google.com";
$location.replace("https://www.google.com");

Only location.href and location.replace will be transformed.

Can't support esbuild-loader, because esbuild transform api does't support plugin.

intercept

return a new path to jump, or return false to stop jump

Related Packages

vite-plugin-remix-router

Remix style file-system routing for React and Vite

4,716 25
@nanostores/router

A tiny (765 bytes) router for Nano Stores state manager

85,222 326
@dark-engine/web-router

The isomorphic Dark router designed for rendering universal web applications tha...

25,069 53
vue-link-interceptor

Vue 3 plugin to intercept all tag clicks in your SPA — handle internal routing a...

5,447 0
vue-router-multi-view

router-view meet v-show meet keep-alive

4,165 86

Version History

Version Released License
0.1.3 MIT
0.1.2 MIT
0.1.1 MIT
0.1.0 MIT
0.0.9 MIT