-->

Remove hash in URL (fullpage.js)

2019-07-18 03:15发布

问题:

I'm using the plugin fullpage.js

Instead of hash urls for the sections like example.com/#sectionname), I would like clean URLs like example.com/sectionname.

The plugin doesn't provide this option but I'm curious if there is a simple enough way to achieve this regardless.

Update 1: I've tried this callback:

onLeave: function(index, nextIndex, direction) {
    if (nextIndex == 2) {
        history.replaceState(null, null, "/about")
    }
}

as well as this:

afterLoad: function(anchorLink, index) {
    if (index == 2) {
        history.replaceState(null, null, "/about");
    }
}

However, when I scroll to the second section, the URL is like this: www.example.com/about/#about.

I've also tried this code:

function locationHashChanged() {
    if (location.hash === "#about") {
        history.replaceState(null, null, "/about");
    }
}
window.onhashchange = locationHashChanged;

However, when new sections are loaded the hash briefly shows before changing to the non hash URL.

回答1:

You can always make use of the HTML 5 history API. You can use callbacks such as onLeave or afterLoad for that:

$('#fullpage').fullpage({
    afterLoad: function(anchorLink, index) {
        history.pushState(null, null, "bar.html");
    }
});

Take into account you'll need to use some polyfill for old browsers. Or just use history.js directly.

Note the example above might not work on localhost on some browsers. You'd better try it in a server.