How to handle browser refresh when using dojo/hash? - javascript

On a single page app, my problem is I'm subscribing to the hashchange event to render the content (create and destroy widgets that represent my pages), but the function only gets fired when the hash actually changes, such as when the browser back and forward buttons are clicked.
My main javascript file that always gets loaded on first time and also on refresh contain the following
topic.subscribe("/dojo/hashchange", function(newhash){
//set content based on hash
});
When refresh is clicked, it doesn't get fired and I'm left with a blank page (all my logic to render the page lies inside the anonymous function for that topic I subscribed to)

your subscribe isn't being called on a refresh as the hash didn't actually change. you're subscribing to hash changes, changes that happen after the page as loaded.
using this subscribe method things can get out of hand quickly. you may want to look at using route. some links -
https://developer.mozilla.org/en-US/docs/Web/Events/hashchange
https://dojotoolkit.org/documentation/tutorials/1.9/hash/
https://dojotoolkit.org/reference-guide/1.10/dojo/router.html
https://www.sitepen.com/blog/2014/06/18/dojo-faq-does-dojo-have-routing-like-backbone-and-embe/

Related

Force Framework7 to Not Remove DOM Elements of Previous Pages

It seems that Framework7 remove DOM elements of previous pages and only keep the previous one. This is problematic since the state is loss as not all interactions are stored in the backend. For example:
Page A > Page B ---> Nothing is removed
Page B > Page C ---> Page A is removed
Then when user click back twice, Page A only shows up only if Page A was fully loaded before addView() function is called. If Page A is loaded afterwards, user will not be taken back to Page A.
Is there any suggestion on how to solve this issue? I looked at the API document and didn't see any option to make sure this doesn't happen.
Update
I managed to get it to go back to Page A by making sure div[data-page] exists before the view is loaded. However, it completely lost the state when returns back to Page A, which is completely useless. Without being able to disable this behavior, I will have a lot of extra code to store every interactions taken by user whether it's done in UI or backend. Let me know if you have any suggestions.
Update 2
I also reported the issue on GitHub. The framework should cache final state of the page rather than original state.
https://github.com/framework7io/Framework7/issues/1985

Detect whether a page is entered through history.back

When I return to a previous page through history.back(), that page is not newly loaded. Instead, it is displayed as it was left. This is good as it is efficient and avoids dribbling in of images.
However, I want to run a function when the page is entered via history.back() to synchronise with the page that is calling history.back(). Is there an event firing in the called page when it is entered in this way [i.e. with history.back()]?
Note: I have a hack using setInterval that polls for re-entry, but think it is ugly. I tried popstate but it did not fire.
You can use
https://github.com/browserstate/history.js/
Especially
History.Adapter.bind(window,'statechange',function()
It fires on every state change ('back' as well).

How do I use window.history in JavaScript?

I found a lot of questions about this on Stack Overflow, but they were all very specific about certain parts. I did find this question whose answers provide some nice references, but they don't actually explain how it all works, and their examples hardly do anything. I want to know more about how it all works together, and I want to use vanilla JavaScript.
(Also, many of the answers on other questions are years old.)
GETTING STARTED
First of all, you can remove the window part. Just history works fine. But before we get into how everything works together, we need to know what we can use.
Important Events
window.onload
This event fires whenever your webpage is loaded. There are two cases that will fire this event:
When your webpage is navigated to from another webpage. Note that I wrote webpage, not website. Moving between pages on the same site will trigger this event.
Just after your webpage is refreshed.
window.onpopstate
This event fires when you navigate between history states that you have set. Your browser automatically sets history states (to null) during normal browsing, but navigating to/from these states will not trigger this event.
window.onunload
This event fires whenever your webpage is unloaded. There are two cases that will fire this event:
When you navigate to another webpage from your webpage.
Just before your webpage is refreshed.
Important Objects
The history interface contains five functions (described below), two read-only objects (described here), and works a bit like a linked list. The two objects contained in each 'link' of the history object are:
length - This is the number of history states for the current browser window. It starts at 1.
state - This is a JavaScript object that can contain practically anything. It is null by default.
You can access them by calling history.length and history.state respectively, though history.state can only be used to get the current history state.
Important Functions
history.go(distance)
This function does the same thing as pressing the back or forward button in your browser, with the added functionality of being able to specify exactly how far you want to go. For example, history.go(3) has the same effect as would pushing your forward button three times, without actually loading the pages between your start and end locations. A negative value will likewise move you backwards through your history. history.go(0), history.go(), and even history.go(NaN) have the same effect as refreshing the page (this does not trigger the popstate event). If you cannot move forward/backward as far as specified, the function will do nothing.
history.back()
This function has the same functionality as the back button in your browser. It is equivalent to history.go(-1). If it cannot go back, the function will do nothing.
history.forward()
This function has the same functionality as the forward button in your browser. It is equivalent to history.go(1). If it cannot go forward, the function will do nothing.
history.replaceState(state, title[, location])
This function replaces the current history state. It takes three arguments, though the last one is optional. The arguments are:
state - This is the most important argument. The object you give to this argument will be saved to history.state for later retrieval. This is a deep copy, so if you later modify the original object it will not change the saved state. You could also set this to null, but if you aren't going to use it, there's not much point in using history at all.
title - The HTML Standard suggests that a string passed to this argument could be used by the browser in the user interface, but no browser currently does anything with it.
location - This argument allows you to change the URL relative to the current page. It cannot be used to change the URL to that of another website, but it can be used to change the URL to that of another page on your website. I would advise against this however, as the page is not actually reloaded even though the URL is of another page. Using back/forward will show the changed URL, but will not change the page, and will trigger popstate rather than load or unload. Refreshing the page after changing its URL will load the page specified by the URL rather than the page you were previously on. This functionality could be used to provide a link to your page in its current state, but I would recommend only changing the query string rather than the full URL. If this argument is not used, the URL will not change.
history.pushState(state, title[, location])
This function works the same as history.replaceState, except it puts the new state after the current state instead of replacing the current state. All history states that could have previously been accessed with forward are discarded, and the new state becomes the current state.
ASSEMBLING THE PIECES
The history interface is very useful for allowing your users to navigate through dynamically generated content from within their browser without having to reload the entire page, but you need to be mindful of all the possible things your users could do that could affect the history state.
First time navigating to your page
Should your users be greeted with a menu/list, some specific dynamically generated content, or maybe some random dynamically generated content?
Will your page display correctly without history, or even JavaScript?
Using back/forward to return to your page
Should your users see the same thing they saw their first time, or should they see the result of their visit reflected in the content? (A "Welcome Back" message might be a nice touch to some, but an unwanted distraction to others.)
Refreshing your page
Should you get a new page, return to the start page, or reload the same page? (Your users probably won't expect that last one if the URL hasn't changed.)
Using back/forward from a refreshed page
Should you get new content relative to the refreshed page, or reload the previously saved state?
Navigating away from your page
Do you need to save anything before leaving?
Returning to your page via a deep link
Do you have code in place to recognize and handle a deep link?
Note there is no way to delete a saved state (other than a specific case with pushState() mentioned above). You can only replace it with new content.
PUTTING IT ALL TOGETHER
Since this is starting to get a bit wordy, lets finish it off with some code.
// This function is called when the page is first loaded, when the page is refreshed,
// and when returning to the page from another page using back/forward.
// Navigating to a different page with history.pushState and then going back
// will not trigger this event as the page is not actually reloaded.
window.onload = function() {
// You can distinguish a page load from a reload by checking performance.navigation.type.
if (window.performance && window.PerformanceNavigation) {
let type = performance.navigation.type;
if (type == PerformanceNavigation.TYPE_NAVIGATE) {
// The page was loaded.
} else if (type == PerformanceNavigation.TYPE_RELOAD) {
// The page was reloaded.
} else if (type == PerformanceNavigation.TYPE_BACK_FORWARD) {
// The page was navigated to by going back or forward,
// though *not* from a history state you have set.
}
}
// Remember that the browser automatically sets the state to null on the
// first visit, so if you check for this and find it to be null, you know
// that the user hasn't been here yet.
if (history.state == null) {
// Do stuff on first load.
} else {
// Do stuff on refresh or on returning to this page from another page
// using back/forward. You may want to make the window.onpopstate function
// below a named function, and just call that function here.
}
// You can of course have code execute in all three cases. It would go here.
// You may also wish to set the history state at this time. This could go in the
// if..else statement above if you only want to replace the state in certain
// circumstances. One reason for setting the state right away would be if the user
// navigates to your page via a deep link.
let state = ...; // There might not be much to set at this point since the page was
// just loaded, but if your page gets random content, or time-
// dependent content, you may want to save something here so it can
// be retrieved again later.
let title = ...; // Since this isn't actually used by your browser yet, you can put
// anything you want here, though I would recommend setting it to
// null or to document.title for when browsers start actually doing
// something with it.
let URL = ...; // You probably don't want to change the URL just yet since the page
// has only just been loaded, in which case you shouldn't use this
// variable. One reason you might want to change the URL is if the
// user navigated to this page with a query string in the URL. After
// reading the query string, you can remove it by setting this
// variable to: location.origin + location.pathname
history.replaceState(state, title, URL); // Since the page has just been loaded, you
// don't want to push a new state; you should
// just replace the current state.
}
// This function is called when navigating between states that you have set.
// Since the purpose of `history` is to allow dynamic content changes without
// reloading the page (ie contacting the server), the code in this function
// should be fairly simple. Just things like replacing text content and images.
window.onpopstate = function() {
// Do things with history.state here.
}
// This function is called right before the page is refreshed, and right
// before leaving the page (not counting history.replaceState). This is
// your last chance to set the page's history state before leaving.
window.onunload = function() {
// Finalize the history state here.
}
Notice that I never called history.pushState anywhere. This is because history.pushState should not be called anywhere in these functions. It should be called by the function that actually changes the page in some way that you want your users to be able to use the back button to undo.
So in conclusion, a generic setup might work like this:
Check if (history.state == null) in the window.onload function.
If true, overwrite the history state with new information.
If false, use the history state to restore the page.
While the user is navigating the page, call history.pushState when important things happen that should be undoable with the back button.
If/When the user uses their back button and the popstate event is triggered, use the history state you set to return the page to its previous state.
Do likewise if/when the user then uses their forward button.
Use the unload event to finalize the history state before the user leaves the page.

what happens when i refresh a jquery mobile page

What happens when a JQUERY MOBILE page is refreshed?
I use ajax to fetch data in a variable called "json" on page1, when user clicks a particular dynamically generated element, i store the id of clicked element in a session variable and changePage() to a new JQM page2 where i use json.thepropertyiwant to generate a list, everything works fine, even back and forward buttons work perfectly however if i refresh page2
then json.thepropertyiwant becomes undefined here is the error i get:
Uncaught TypeError: Cannot read property 'responseData' of undefined
i am using a multipage in a single html5 page model
edit:
I have used variable name json and not JSON i just typed it like
that to emphasize, however now i think that was foolish!
I have also figured my problem. My mistake was that i was assuming
page refresh would call pageinit for the page i am on but it works
no differently than a normal html page refresh and triggers
document.ready each time and then pageinit for the page i am on.
Is there a way to listen to a
pagerefresh event and override its normal functionality?
I believe that you generate the dynamic content of page2 in some event.
I believe that the event is pageinit or pagecreate. Those events fire only once (if you have ajax page load set to true).
What happens is that you request the data when you load page1 (something like pageinit?)
When you refresh page2, the data is not there because the event that you request your data in, is not firing, which is completely normal, because when you refresh page2, page1 has nothing to do with it. Post the section of your code where you request your data, and the section where you generate the dynamic content for page2 for more.
Hmm... there's a few issues going on here.
For starters, don't use a variable called 'JSON'. That's no good - there's already a global object called JSON which is used for parsing and encoding JSON! You could accidentally overwrite it.
As you discovered, if you store data in a variable in javascript - that variable is only in memory for the current page. If you refresh the page, then that variable will no longer be in memory.
But that's not really anything to do with jQuery Mobile. That's just how web browsers work - javascript structures created in-memory are not persisted between page refreshes.
Generally you need to save the data yourself using localStorage or cookies for it to persist between page refreshes.
Typically you don't refresh a jQuery Mobile app anyway. So the previous point is generally not too much of an issue. A user refreshing the page is like rebooting the app.
The app should when it starts reload any data that it needs, i.e.
from localStorage, from cookies, or make some new ajax calls to
reload. You would have to program that logic in.

history.pushState - not working?

I want to change html without reload. I do it like:
$('#left_menu_item').click(function(e) {
if (!!(window.history && history.pushState)) {
e.preventDefault();
history.pushState(null, null, newUrl);
}
});
It works correctly. But if I want to go back with "Back" button - browser change url on previous, but it not reload page. Why?
this behaviour is expected and is in accordance with the specifications of manipulating the history stack.
this is a relatively complex problem to explain. but in short think of it as this: any history entry the user pushes on the history stack (using pushState etc) doesn't merit a page load when you move from it because it is considered a fake (user generated) history entry.
why?
this behaviour is a good thing and is consistent with the intent of giving the developer more control over the page without being forced to reload it (think of it like ajax: you can do things that were previously only possible by page reloading like fetching data but now you can do it without reloading the page using the XMLHttpRequest object).. if you want to mimic the behaviour of reloading the page when clicking the back button.. you can simply call location.reload() when you handle the window.onpopstate event
how?
this may be outside the scope of your question but i just wanted to put it there to describe what we're talking about
let me explain by using an existing example here (excerpted text will be italicised):
Suppose http://mozilla.org/foo.html executes the following JavaScript:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
think of it as that you are creating an entry in the history stack that is not associated with an actual page load.. rather a 'fake' page load (ie you are just using javascript to manipulate the dom and insert html)..
Suppose now that the user now navigates to http://google.com, then clicks back. At this point, the URL bar will display http://mozilla.org/bar.html, and the page will get a popstate event whose state object contains a copy of stateObj. The page itself will look like foo.html, although the page might modify its contents during the popstate event.
the point here is that bar.html is a fake history entry that sits on top of the original http://mozilla.org/foo.html.. so you will see on the url http://mozilla.org/bar.html but the contents will belong to foo (in this example notice that we didnt manipulate the content of the dom when we pushed bar.html.. if we did like in your example.. then that content will also show up). the key thing here is that the page reloads!.. because we are serving a page that has a genuin entry on the history stack (even if on the url.. we are displaying a url that is associated with a fake entry on the history stack).
also separate this discussion from the page manually handling the popstate event.. that's a different story and will just complicate things.
If we click back again, the URL will change to http://mozilla.org/foo.html, and the document will get another popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.
here.. the page will not load!.. that's because we are making the transfer from a fake history stack entry to the real one (and the real one was already loaded in the previous step.. so the page reloaded and that's it).
that's it for the example. the concept is kind of hard to explain and i encourage you to test your code by clicking through a combination of real and fake pages and you will see a pattern of when the page actually loads and when it doesn't..
window.onpopstate = function(event) {
if(event && event.state) {
location.reload();
}
}
This is what I use :)

Categories

Resources