Remove hash in URL (fullpage.js)

2019-07-18 03:35发布

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条回答
地球回转人心会变
2楼-- · 2019-07-18 04:07

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.

查看更多
登录 后发表回答