包详细信息

page

visionmedia145.3kMIT1.11.6

Tiny client-side router

自述文件

page router logo

Tiny Express-inspired client-side router.

Build Status Coverage Status Gitter

page('/', index)
page('/user/:user', show)
page('/user/:user/edit', edit)
page('/user/:user/album', album)
page('/user/:user/album/sort', sort)
page('*', notfound)
page()

Installation

There are multiple ways to install page.js. With package managers:

  $ npm install page # for browserify
  $ component install visionmedia/page.js
  $ bower install visionmedia/page.js

Or use with a CDN. We support:

  • cdnjs
  • unpkg

    Using with global script tags:

    <script src="https://unpkg.com/page/page.js"></script>
    <script>
    page('/about', function(){
      // Do stuff
    });
    </script>
    

    Or with modules, in modern browsers:

    <script type="module">
    import page from "//unpkg.com/page/page.mjs";
    
    page('/home', () => { ... });
    </script>
    

Running examples

To run examples do the following to install dev dependencies and run the example server:

$ git clone git://github.com/visionmedia/page.js
$ cd page.js
$ npm install
$ node examples
$ open http://localhost:4000

Currently we have examples for:

  • basic minimal application showing basic routing
  • notfound similar to basic with single-page 404 support
  • album showing pagination and external links
  • profile simple user profiles
  • query-string shows how you can integrate plugins using the router
  • state illustrates how the history state may be used to cache data
  • server illustrates how to use the dispatch option to server initial content
  • chrome Google Chrome style administration interface
  • transitions Shows off a simple technique for adding transitions between "pages"
  • partials using hogan.js to render mustache partials client side

    NOTE: keep in mind these examples do not use jQuery or similar, so portions of the examples may be relatively verbose, though they're not directly related to page.js in any way.

API

page(path, callback[, callback ...])

Defines a route mapping path to the given callback(s). Each callback is invoked with two arguments, context and next. Much like Express invoking next will call the next registered callback with the given path.

page('/', user.list)
page('/user/:id', user.load, user.show)
page('/user/:id/edit', user.load, user.edit)
page('*', notfound)

Under certain conditions, links will be disregarded and will not be dispatched, such as:

  • Links that are not of the same origin
  • Links with the download attribute
  • Links with the target attribute
  • Links with the rel="external" attribute

page(callback)

This is equivalent to page('*', callback) for generic "middleware".

page(path)

Navigate to the given path.

$('.view').click(function(e){
  page('/user/12')
  e.preventDefault()
})

page(fromPath, toPath)

Setup redirect from one path to another.

page.redirect(fromPath, toPath)

Identical to page(fromPath, toPath)

page.redirect(path)

Calling page.redirect with only a string as the first parameter redirects to another route. Waits for the current route to push state and after replaces it with the new one leaving the browser history clean.

page('/default', function(){
  // some logic to decide which route to redirect to
  if(admin) {
    page.redirect('/admin');
  } else {
    page.redirect('/guest');
  }
});

page('/default');

page.show(path)

Identical to page(path) above.

page([options])

Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:

  • click bind to click events [true]
  • popstate bind to popstate [true]
  • dispatch perform initial dispatch [true]
  • hashbang add #! before urls [false]
  • decodeURLComponents remove URL encoding from path components (query string, pathname, hash) [true]
  • window provide a window to control (by default it will control the main window)

    If you wish to load serve initial content from the server you likely will want to set dispatch to false.

page.start([options])

Identical to page([options]) above.

page.stop()

Unbind both the popstate and click handlers.

page.base([path])

Get or set the base path. For example if page.js is operating within /blog/* set the base path to "/blog".

page.strict([enable])

Get or set the strict path matching mode to enable. If enabled /blog will not match "/blog/" and /blog/ will not match "/blog".

page.exit(path, callback[, callback ...])

Defines an exit route mapping path to the given callback(s).

Exit routes are called when a page changes, using the context from the previous change. For example:

page('/sidebar', function(ctx, next) {
  sidebar.open = true
  next()
})

page.exit('/sidebar', function(ctx, next) {
  sidebar.open = false
  next()
})

page.exit(callback)

Equivalent to page.exit('*', callback).

page.create([options])

Create a new page instance with the given options. Options provided are the same as provided in page([options]) above. Use this if you need to control multiple windows (like iframes or popups) in addition to the main window.

var otherPage = page.create({ window: iframe.contentWindow });
otherPage('/', main);

page.clickHandler

This is the click handler used by page to handle routing when a user clicks an anchor like <a href="/user/profile">. This is exported for those who want to disable the click handling behavior with page.start({ click: false }), but still might want to dispatch based on the click handler's logic in some scenarios.

Context

Routes are passed Context objects, these may be used to share state, for example ctx.user =, as well as the history "state" ctx.state that the pushState API provides.

Context#save()

Saves the context using replaceState(). For example this is useful for caching HTML or other resources that were loaded for when a user presses "back".

Context#handled

If true, marks the context as handled to prevent default 404 behaviour. For example this is useful for the routes with interminate quantity of the callbacks.

Context#canonicalPath

Pathname including the "base" (if any) and query string "/admin/login?foo=bar".

Context#path

Pathname and query string "/login?foo=bar".

Context#querystring

Query string void of leading ? such as "foo=bar", defaults to "".

Context#pathname

The pathname void of query string "/login".

Context#state

The pushState state object.

Context#title

The pushState title.

Routing

The router uses the same string-to-regexp conversion that Express does, so things like ":id", ":id?", and "*" work as you might expect.

Another aspect that is much like Express is the ability to pass multiple callbacks. You can use this to your advantage to flatten nested callbacks, or simply to abstract components.

Separating concerns

For example suppose you have a route to edit users, and a route to view users. In both cases you need to load the user. One way to achieve this is with several callbacks as shown here:

page('/user/:user', load, show)
page('/user/:user/edit', load, edit)

Using the * character we can alter this to match all routes prefixed with "/user" to achieve the same result:

page('/user/*', load)
page('/user/:user', show)
page('/user/:user/edit', edit)

Likewise * can be used as catch-alls after all routes acting as a 404 handler, before all routes, in-between and so on. For example:

page('/user/:user', load, show)
page('*', function(){
  $('body').text('Not found!')
})

Default 404 behaviour

By default when a route is not matched, page.js invokes page.stop() to unbind itself, and proceed with redirecting to the location requested. This means you may use page.js with a multi-page application without explicitly binding to certain links.

Working with parameters and contexts

Much like request and response objects are passed around in Express, page.js has a single "Context" object. Using the previous examples of load and show for a user, we can assign arbitrary properties to ctx to maintain state between callbacks.

To build a load function that will load the user for subsequent routes you'll need to access the ":id" passed. You can do this with ctx.params.NAME much like Express:

function load(ctx, next){
  var id = ctx.params.id
}

Then perform some kind of action against the server, assigning the user to ctx.user for other routes to utilize. next() is then invoked to pass control to the following matching route in sequence, if any.

function load(ctx, next){
  var id = ctx.params.id
  $.getJSON('/user/' + id + '.json', function(user){
    ctx.user = user
    next()
  })
}

The "show" function might look something like this, however you may render templates or do anything you want. Note that here next() is not invoked, because this is considered the "end point", and no routes will be matched until another link is clicked or page(path) is called.

function show(ctx){
  $('body')
    .empty()
    .append('<h1>' + ctx.user.name + '<h1>');
}

Finally using them like so:

page('/user/:id', load, show)

NOTE: The value of ctx.params.NAME is decoded via decodeURIComponent(sliceOfUrl). One exception though is the use of the plus sign (+) in the url, e.g. /user/john+doe, which is decoded to a space: ctx.params.id == 'john doe'. Also an encoded plus sign (%2B) is decoded to a space.

Working with state

When working with the pushState API, and page.js you may optionally provide state objects available when the user navigates the history.

For example if you had a photo application and you performed a relatively extensive search to populate a list of images, normally when a user clicks "back" in the browser the route would be invoked and the query would be made yet-again.

An example implementation might look as follows:

function show(ctx){
  $.getJSON('/photos', function(images){
    displayImages(images)
  })
}

You may utilize the history's state object to cache this result, or any other values you wish. This makes it possible to completely omit the query when a user presses back, providing a much nicer experience.

function show(ctx){
  if (ctx.state.images) {
    displayImages(ctx.state.images)
  } else {
    $.getJSON('/photos', function(images){
      ctx.state.images = images
      ctx.save()
      displayImages(images)
    })
  }
}

NOTE: ctx.save() must be used if the state changes after the first tick (xhr, setTimeout, etc), otherwise it is optional and the state will be saved after dispatching.

Matching paths

Here are some examples of what's possible with the string to RegExp conversion.

Match an explicit path:

page('/about', callback)

Match with required parameter accessed via ctx.params.name:

page('/user/:name', callback)

Match with several params, for example /user/tj/edit or /user/tj/view.

page('/user/:name/:operation', callback)

Match with one optional and one required, now /user/tj will match the same route as /user/tj/show etc:

page('/user/:name/:operation?', callback)

Use the wildcard char * to match across segments, available via ctx.params[N] where N is the index of * since you may use several. For example the following will match /user/12/edit, /user/12/albums/2/admin and so on.

page('/user/*', loadUser)

Named wildcard accessed, for example /file/javascripts/jquery.js would provide "/javascripts/jquery.js" as ctx.params.file:

page('/file/:file(.*)', loadUser)

And of course RegExp literals, where the capture groups are available via ctx.params[N] where N is the index of the capture group.

page(/^\/commits\/(\d+)\.\.(\d+)/, loadUser)

Plugins

An example plugin examples/query-string/query.js demonstrates how to make plugins. It will provide a parsed ctx.query object derived from node-querystring.

Usage by using "*" to match any path in order to parse the query-string:

page('*', parse)
page('/', show)
page()

function parse(ctx, next) {
  ctx.query = qs.parse(location.search.slice(1));
  next();
}

function show(ctx) {
  if (Object.keys(ctx.query).length) {
    document
      .querySelector('pre')
      .textContent = JSON.stringify(ctx.query, null, 2);
  }
}

Available plugins

Please submit pull requests to add more to this list.

Running tests

In the console:

$ npm install
$ npm test

In the browser:

$ npm install
$ npm run serve
$ open http://localhost:3000/

Support in IE8+

If you want the router to work in older version of Internet Explorer that don't support pushState, you can use the HTML5-History-API polyfill:

  npm install html5-history-api
How to use a Polyfill together with router (OPTIONAL):

If your web app is located within a nested basepath, you will need to specify the basepath for the HTML5-History-API polyfill. Before calling page.base() use: history.redirect([prefixType], [basepath]) - Translation link if required.

  • prefixType: [string|null] - Substitute the string after the anchor (#) by default "/".
  • basepath: [string|null] - Set the base path. See page.base() by default "/". (Note: Slash after pathname required)

Pull Requests

  • Break commits into a single objective.
  • An objective should be a chunk of code that is related but requires explanation.
  • Commits should be in the form of what-it-is: how-it-does-it and or why-it's-needed or what-it-is for trivial changes
  • Pull requests and commits should be a guide to the code.

Server configuration

In order to load and update any URL managed by page.js, you need to configure your environment to point to your project's main file (index.html, for example) for each non-existent URL. Below you will find examples for most common server scenarios.

Nginx

If using Nginx, add this to the .conf file related to your project (inside the "server" part), and reload your Nginx server:

location / {
    try_files $uri $uri/ /index.html?$args;
}

Apache

If using Apache, create (or add to) the .htaccess file in the root of your public folder, with the code:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^.*$ ./index.html

Node.js - Express

For development and/or production, using Express, you need to use express-history-api-fallback package. An example:

import { join } from 'path';
import express from 'express';
import history from 'express-history-api-fallback';

const app = express();
const root = join(__dirname, '../public');

app.use(express.static(root));
app.use(history('index.html', { root }));

const server = app.listen(process.env.PORT || 3000);

export default server;

Node.js - Browsersync

For development using Browsersync, you need to use history-api-fallback package. An example:

var browserSync = require("browser-sync").create();
var historyApiFallback = require('connect-history-api-fallback');

browserSync.init({
    files: ["*.html", "css/*.css", "js/*.js"],
    server: {
        baseDir: ".",
        middleware: [ historyApiFallback() ]
    },
    port: 3030
});

Integrations

License

(The MIT License)

Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

更新日志

1.8.3 / 2018-01-22

This is a patch release which switches the build to rollup. Switching shaves 2k off of the gzipped size. In addition to this benefit, this also fixes a couple of small issues:

Issues

  • #444 - Closure compiler warnings
  • #458 - unsafe-eval error

1.8.2 / 2018-01-22

This is a patch release fixing an issue that was meant to be solved in 1.8.1. page.js now runs in Node.js again, when there isn't a window environment.

1.8.1 / 2018-01-22

This is a patch release, fixing an issue with Node.js usage.

1.8.0 / 2018-01-17

This is a minor release, adding one new (minor) feature and a few bug fixes and documentation improvements.

Controlling other pages

The new feature of this release is that page.js can now control other pages (windows) besides the main window. This makes it possible to control an iframe's routing. You can use it by passing the window option to start:

page('/', function(){
  // Whoa, I'm inside an iframe!
});

page.start({ window: myiFrame.contentWindow });

Note that page is still a singleton, which means you can only have 1 page, so you can't control both an iframe and the main window at the same time.

This change was made to improve our testing, but in the future we'll make it possible to have multiple page objects so you really will be able to control multiple iframes and the main window all at the same time.

Better hashbang support

Hashbang support has never been very good in page.js. But we're slowly improving it! In 1.8.0 we've fixed the problem where the app's full URL would show up in the hashbang upon start. http://example.com/my/page#!/my/page. Gross! No longer happens thanks to #447.

Pull Requests

Those are the big things, but here's a list of all of the pull requests merged into 1.8.0:

  • #445 - Prevent hash from being part of the ctx.pathname
  • #447 - Prevent going to the root when setting up the initial hashchange route
  • #446 - Add a note about usage with a CDN
  • #443 - Change test infrastructure to run inside of iframes
  • #303 - page.exit callback example missing context param
  • #267 - Added clarification for decoded plus signs in urls

1.7.3 / 2018-01-15

This is a patch release making an improvement to how page.js works on pages that use the file protocol, such as Electron and nw.js apps.

Pull Requests

  • #441 - Set the page's base to be the current location when used under the file protocol with hashbang routing.

1.7.2 / 2018-01-15

Our first release in almost 2 years! This is a long overdue patch release that contains various bug fixes that have taken place over the course of the last couple of years. As releases will become much more often in the future (containing only a few fixes in most cases), I will be listing the closed issues in releases, but because there are 2 years worth it is not practical to do so in this release.

While you're here, if you haven't checked out page.js in a long time now is a great time. I've recently taken over maintenance and have a plan in place to take this great small library into the future. For now I am concentrating on stabilizing 1.x by fixing as many of the backlog of issues that have built up as I can. Once that is complete we'll start thinking about 2.0.

If you've submitted a PR here in the past and seen it be ignored, please come back! Your contributions are invaluable, and I promise that as long as I'm maintaining this project I'll do my best to always at least comment on pull requests and try to get them resolved.

That's all for now! Please report any issues you find in 1.7.2.

1.7.1 / 2016-03-17

  • #363 - Reinstate shadow DOM fixes which were reverted

1.7.0 / 2016-03-12

1.6.4 / 2015-10-09

  • fix wildcard route support (update path-to-regexp to v1.2.1)

1.6.3 / 2015-04-19

  • fix including page.js on server side
  • fix including page.js if the document is already loaded
  • fix bug with click-event in Firefox

1.6.2 / 2015-03-06

  • fix touch support #236
  • fix nw.js support #238
  • fix popstate issue in Safari #213

1.6.1 / 2015-02-16

  • added page.js to npm files
  • back button works correct with hash links in Firefox #218

1.6.0./ 2015-01-27

  • added page.back feature #157
  • added decodeURLComponents option #187
  • now ctx.params is object like in express #203
  • skip route processing if another one is called #172
  • docs improved
  • tests improved

1.5.0 / 2014-11-29

  • added page.exit(path, callback[, callback...])
  • added page.redirect(url)
  • fix: ignore links with download attribute
  • fix: remove URL encoding before parsing paths

1.4.1 / 2014-11-14

  • fixed: hashbang navigation
  • added hashbang example
  • added tests

1.4.0 / 2014-11-12

  • add hashbang support. Closes #112
  • add page.redirect() method
  • add plugins list to readme
  • add Context#handled option
  • Fix an issue where redirects in dispatch can be overwritten by ctx.save()
  • add support HTML5-History-API polyfill
  • make sameOrigin public
  • update path-to-regexp
  • allow for missing href in anchors.
  • update examples

1.3.7 / 2013-09-09

  • fix removal of fragment

1.3.6 / 2013-03-12

  • fix links with target attribute

1.3.5 / 2013-02-12

  • fix ctrl/cmd/shift clicks

1.3.4 / 2013-02-04

  • add tmp .show() dispatch argument
  • add keywords to component.json

1.3.3 / 2012-12-14

  • remove + support from path regexps

1.3.2 / 2012-11-26

  • add explicit "#" check
  • add window to addEventListener calls

1.3.1 / 2012-09-21

  • fix: onclick only when e.which == 1

1.3.0 / 2012-08-29

  • add page(fn) support. Closes #27
  • add component.json
  • fix tests
  • fix examples

1.2.1 / 2012-08-02

  • add transitions example
  • add exposing of Context and Route constructors
  • fix infinite loop issue unhandled paths containing query-strings

1.2.0 / 2012-07-05

  • add ctx.pathname
  • add ctx.querystring
  • add support for passing a query-string through the dispatcher [ovaillancourt]
  • add .defaultPrevented support, ignoring page.js handling [ovaillancourt]

1.1.3 / 2012-06-18

  • Added some basic client-side tests
  • Fixed initial dispatch in Firefox
  • Changed: no-op on subsequent page() calls. Closes #16

1.1.2 / 2012-06-13

  • Fixed origin portno bug preventing :80 and :443 from working properly
  • Fixed: prevent cyclic refreshes. Closes #17

1.1.1 / 2012-06-11

  • Added enterprisejs example
  • Added: join base for .canonicalPath. Closes #12
  • Fixed location.origin usage [fisch42]
  • Fixed pushState() when unhandled

1.1.0 / 2012-06-06

  • Added + support to pathtoRegexp()
  • Added page.base(path) support
  • Added dispatch option to page(). Closes #10
  • Added Context#originalPath
  • Fixed unhandled links when .base is present. Closes #11
  • Fixed: Context#path to "/"

0.0.2 / 2012-06-05

  • Added make clean
  • Added some mocha tests
  • Fixed: ignore fragments
  • Fixed: do not pushState on initial load