How to manage browser “back” and “forward” buttons when creating a javascript widget

前端 未结 1 755
抹茶落季
抹茶落季 2021-01-25 13:10

I have created a Javascript widget that allows user to embed a calendar on external websites. Right now i\'m not handling browser back/forward button in any way, that means that

相关标签:
1条回答
  • 2021-01-25 13:21

    There are two main methods for achieving what you are after.
    One of them, is the hash method you've mentioned. If you need to support older browsers (IE <= 9), that's the way to go. If you decide to use this method, your friend is the hashchange event. The hash pattern relies on this event in order to trigger functionality. In its most naive way it will look something like:

    window.addEventListener('hashchange', function (e) {
        var hash = window.location.hash;
        if (hash === 'event-1') {
            // ...
        }
        else if (...) {
            // ...
        }
    });
    

    Your other option, is to use the History API, specifically - the pushState method, alongside the popstate event. It should be noted that the pushState method does not create an HTTP request. Also, if the user changes the current history entry (with the back/forward buttons), the browser will not reload, but instead, will trigger a popstate event, that you can listen to. If the user if navigating to a history entry that was not created using pushState or replaceState, the browser will load the resource as expected (you won't harm the user's experience - if she wants to get out of the website, she'll succeed).

    Note that using the hashchange method might conflict with other libraries that use that method, and since most popular frameworks (ember, angular, etc..) use that method for browser compatibility reasons, it is kinda risky.

    For your concern regarding the 'non existing page' problem - A possible solution is to use query params for your state, and not non-existing URLs:

    window.history.pushState({ event: 'event-id' }, "Event Title", "?event=event-id");
    

    You can then parse the query-parameters on page-load, and use their values in order to initialize your component in the desired state.

    You can take a look at this nice MDN article for better reference.

    0 讨论(0)
提交回复
热议问题