Using $location for only part of a page breaks back button - javascript

I want to use $location to navigate a self-contained comments section on a normal statically loaded page, but it seems to break the back back button.
The problem comes when I've navigated to a few pages using $location, then click on an external link. It goes to that link, but when I hit back, it changes the URL to the last one but doesn't actually change the page (i.e. it stays on the external page). If I then keep on clicking back, it changes the URL (so the url history is fine), but it doesn't actually load up the page from that url until I get to the first one that I've visited (if that makes sense...). So, for example:
So, navigating the app:
www.example.com - loads up my page with the comments
www.example.com?page=2 - uses $location and loads the new comments correctly
www.example.com?page=3 - uses $location and loads the new comments correctly
www.externalexamplepage.com - navigates correctly to the page.
back - changes the address to www.example.com?page=3 but stays on www.externalexamplepage.com
back - changes the address to www.example.com?page=2 but stays on www.externalexamplepage.com
back - changes the address to www.example.com and loads up the page correctly.
So, how can I get it to not break the back button? This is what I've got in my comments directive:
$scope.$on('$locationChangeStart', function(e, newUrl) {
// If moving off current page...
if ($scope.changingCommentsPage === false) {
$window.location.href = newUrl;
}
});
$scope.$on('$locationChangeSuccess', function() {
// Get current urlParams
var urlParams = $location.search();
// Get new comments if page has changed
if ($scope.page != urlParams.page || typeof urlParams.page === "undefined") {
$scope.changingCommentsPage = false;
$scope.page = urlParams.page ? urlParams.page : 1;
if ($scope.page < 1) return;
// Get comments
getComments($scope.model.page);
}
});

Related

Contents of reports getting overwritten . Need to refresh parent page?

Please find the summary of my query:-
Lets say I start off at my homepage :- https://example.com//homepage
At the homepage I have links to certain documents .Once I click on one of the links it takes me to a page where I am asked to fill information and I can finally submit it.
I fill the information ,click on submit it takes me to final signature page where it asks me to enter my credentials so that it can post a timestamp saying that I have authored this document at this particular time.
Now I close this window and return to the homepage and click on another document link ,WITHOUT REFRESHING THE HOMEPAGE and follow the same steps. For some some odd reason when I complete this document I see that details mentioned in the first report have been leaked\merged\overwritten into this document.BIZZARE!!
So I did a bit of research(soul searching if you may say) and I found the reason could be because the session is still having the old data from the old document ?Basically what I tried was when I manually refreshed the homepage ,this issue didn't occur. So what I am trying to do now is ,every time I SIGN off the document, i.e reach the final signature page and click no 'SUBMIT' button , I want the homepage ,viz https://example.com/homepage to refresh.
Below is the snippet of JSCRIPT that is being called when I click on 'SUBMIT' button on the signature page:-(this is basically the onclick function for that 'SUBMIT' HTML function )
function completeForm(aForm)
{
var foundError = false;
if(validateRequiredInput(aForm.loginID) &
validateRequiredInput(aForm.password) )
{
document.getElementById("submitBtn").disabled = true;
// Modified to get the newWindow request Parameter by Nidhi Prakash Srivastava for clinSIGHT release 2.0.6
var newWindow = "";
if(aForm.getNewWindow != null)
{
newWindow=aForm.getNewWindow.value;
}
// Modified to get the newEPCWindow request Parameter by Nidhi Prakash Srivastava for clinSIGHT release 2.0.10
var newEPCWindow = "";
var newQCWindow = "";
if(aForm.getNewEPCWindow != null && aForm.action.indexOf("?") < 0)
{
newEPCWindow=aForm.getNewEPCWindow.value;
aForm.action = aForm.action+"?op=complete&newWindow="+newWindow+"&newEPCWindow="+newEPCWindow;
}else if(aForm.getNewQCWindow != null && aForm.action.indexOf("?") < 0){
newQCWindow=aForm.getNewQCWindow.value;
aForm.action = aForm.action+"?op=complete&newWindow="+newWindow+"&newQCWindow="+newQCWindow;
}else if(aForm.action.indexOf("?") < 0)
{
aForm.action = aForm.action+"?op=complete&newWindow="+newWindow;
}
onsubmitFormHandler();
aForm.submit();
}
How do I go about achieveing the refresh of the homepage from here? Is this even the right approach ? Any suggestions on the same ?

Ionic Navigation Controller - check if page has been loaded already

Ok..I notice that each time I push a new page in the navigation controller, the page is rendered the page state is always the default.
Lets say a user goes to a page, modifies some data, later comes back to the page and his changes are gone.
Is there any way I can restore the page, in case he has already been there?
Here is my idea for now, I was wondering if there was a better approach?
//Check if page was not visited already
console.log('Check if page was not already loaded.')
let restoredFromHistory = false;
this.navCtrl.getViews().forEach( view => {
if(view.name == 'CartPage'){
console.log('Page was found in the history.')
this.navCtrl.push(view);
restoredFromHistory = true;
}
})
if(!restoredFromHistory){
console.log('Page was not found in the history. Pushing a brand new.')
this.navCtrl.push(CartPage)
}

URL routing not working when user clicks a link

I am trying to modify a web application we have and I'm not sure if I can do what is being requested. My boss wants to be able to click a link from an email and have our internal company web application go straight to a page identified at the end of a provided URL.
If I click on the link below the first time, it goes to the index page of our web application. If I leave the web application open and click on the link again, it goes to the correct page identified at the end of the URL.
http://mycompanyweb.com/handbook/mycompanyprocess/#/rt/softwate/9.13_UpdateSDP
I've tried adding an init(), thinking that is where the application goes first in the lifecycle and I only see this part of the URL at that point (http://mycompanyweb.com/handbook/mycompanyprocess/). This leads me to believe that the browser is stripping everything off after the # when it first opens. Is that correct? Is there something I can do to get our web application to go directly to the document the first time a user clicks on the link, without the web application open?
http://mycompanyweb.com/handbook/mycompanyprocess/ - Base URL
#/rt - Used by our javascript engine to determine which path to take
(dev or production).
/software/9.13_UpdateSDP - Logical path to a web page named 6.034_UpdateSDP.htm
Our engine that determines where to route based on the URL. I assume that the second time a link is clicked that it goes to the correct page is because the engine has been loaded (provided the browser is left open when clicked a second time).
$(document).ready(function () {
// Define the routes.
Path.map("#/:program").to(function () {
var program = this.params['program'];
if (program == "search") {
$("#mainContent").load("search.html");
}
else {
$("#mainContent").load("views/onepageprocess.html");
}
$("#subheader").html("");
$("#headerLevelTwoBreadcrumbLink").html("");
}).enter(setPageActions);
Path.map("#/:program/:swimlane").to(function () {
localStorage.removeItem("SearchString");
var swimlane = this.params['swimlane'];
var view = "views/" + swimlane + ".html";
$("#mainContent").load(view);
}).enter(setPageActions);
// Sends all links to the level three view and updates the breadcrumb.
Path.map("#/:program/:swimlane/:page").to(function () {
var page = this.params['page'];
var url = "views/levelthree/" + page.replace("", "") + ".htm";
var levelThreeTitle = "";
$.get(url)
.done(function () {
// Nothing here at this time...
}).fail(function () {
url = "views/levelthree/badurlpage.htm";
levelThreeTitle = "Page Unavailable";
}).always(function (data) {
$("#subheader").html("");
level_three_breadcrumb = "views/breadcrumbs/breadcrumb_link.html";
$("#headerLevelTwoBreadcrumbLink").load(level_three_breadcrumb);
$("#headerLevelThreeBreadcrumb").html("");
$('#headerLevelThreeBreadcrumb').append('<img src="images/Chevron.gif" />');
if (data.status != "404") {
$("#headerLevelThreeBreadcrumb").append(retrieveStorageItem("LevelThreeSubheader"));
}
$("#mainContent").load(url);
});
}).enter(setPageActions);
// Set a "root route". User will be automatically re-directed here. The definition
// below tells PathJS to load this route automatically if one isn't provided.
Path.root("#/rt");
// Start the path.js listener.
Path.listen();
});
Is there something I can do to get our web application to go directly to the document the first time a user clicks on the link, without the web application open?
If anyone runs into something like this, I found out that my company's servers were stripping anything after the # in the URL at authentication. I will be modifying my app to not use hash tags in the URL to fix it.

Ajax with history.pushState and popstate - what do I do when popstate state property is null?

I'm trying out the HTML5 history API with ajax loading of content.
I've got a bunch of test pages connected by relative links. I have this JS, which handles clicks on those links. When a link is clicked the handler grabs its href attribute and passes it to ajaxLoadPage(), which loads content from the requested page into the content area of the current page. (My PHP pages are set up to return a full HTML page if you request them normally, but only a chunk of content if ?fragment=true is appended to the URL of the request.)
Then my click handler calls history.pushState() to display the URL in the address bar and add it to the browser history.
$(document).ready(function(){
var content = $('#content');
var ajaxLoadPage = function (url) {
console.log('Loading ' + url + ' fragment');
content.load(url + '?fragment=true');
}
// Handle click event of all links with href not starting with http, https or #
$('a').not('[href^=http], [href^=https], [href^=#]').on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
ajaxLoadPage(href);
history.pushState({page:href}, null, href);
});
// This mostly works - only problem is when popstate happens and state is null
// e.g. when we try to go back to the initial page we loaded normally
$(window).bind('popstate', function(event){
console.log('Popstate');
var state = event.originalEvent.state;
console.log(state);
if (state !== null) {
if (state.page !== undefined) {
ajaxLoadPage(state.page);
}
}
});
});
When you add URLs to the history with pushState you also need to include an event handler for the popstate event to deal with clicks on the back or forward buttons. (If you don't do this, clicking back shows the URL you pushed to history in the address bar, but the page isn't updated.) So my popstate handler grabs the URL saved in the state property of each entry I created, and passes it to ajaxLoadPage to load the appropriate content.
This works OK for pages my click handler added to the history. But what happens with pages the browser added to history when I requested them "normally"? Say I land on my first page normally and then navigate through my site with clicks that do that ajax loading - if I then try to go back through the history to that first page, the last click shows the URL for the first page, but doesn't load the page in the browser. Why is that?
I can sort of see this has something to do with the state property of that last popstate event. The state property is null for that event, because it's only entries added to the history by pushState() or replaceState() that can give it a value. But my first loading of the page was a "normal" request - how come the browser doesn't just step back and load the initial URL normally?
This is an older question but there is a much simpler answer using native javascript for this issue.
For the initial state you should not be using history.pushState but rather history.replaceState.
All arguments are the same for both methods with the only difference is that pushState creates a NEW history record and thus is the source of your problem. replaceState only replaces the state of that history record and will behave as expected, that is go back to the initial starting page.
I ran into the same issue as the original question. This line
var initialPop = !popped && location.href == initialURL;
should be changed to
var initialPop = !popped;
This is sufficient to catch the initial pop. Then you do not need to add the original page to the pushState. i.e. remove the following:
var home = 'index.html';
history.pushState({page:home}, null, home);
The final code based on AJAX tabs (and using Mootools):
if ( this.supports_history_api() ) {
var popped = ('state' in window.history && window.history.state !== null)
, changeTabBack = false;
window.addEvent('myShowTabEvent', function ( url ) {
if ( url && !changingTabBack )
setLocation(url);
else
changingTabBack = false;
//Make sure you do not add to the pushState after clicking the back button
});
window.addEventListener("popstate", function(e) {
var initialPop = !popped;
popped = true;
if ( initialPop )
return;
var tabLink = $$('a[href="' + location.pathname + '"][data-toggle*=tab]')[0];
if ( tabLink ) {
changingTabBack = true;
tabLink.tab('show');
}
});
}
I still don't understand why the back button behaves like this - I'd have thought the browser would be happy to step back to an entry that was created by a normal request. Maybe when you insert other entries with pushState the history stops behaving in the normal way. But I found a way to make my code work better. You can't always depend on the state property containing the URL you want to step back to. But stepping back through history changes the URL in the address bar as you would expect, so it may be more reliable to load your content based on window.location. Following this great example I've changed my popstate handler so it loads content based on the URL in the address bar instead of looking for a URL in the state property.
One thing you have to watch out for is that some browsers (like Chrome) fire a popstate event when you initially hit a page. When this happens you're liable to reload your initial page's content unnecessarily. So I've added some bits of code from the excellent pjax to ignore that initial pop.
$(document).ready(function(){
// Used to detect initial (useless) popstate.
// If history.state exists, pushState() has created the current entry so we can
// assume browser isn't going to fire initial popstate
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
var content = $('#content');
var ajaxLoadPage = function (url) {
console.log('Loading ' + url + ' fragment');
content.load(url + '?fragment=true');
}
// Handle click event of all links with href not starting with http, https or #
$('a').not('[href^=http], [href^=https], [href^=#]').on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
ajaxLoadPage(href);
history.pushState({page:href}, null, href);
});
$(window).bind('popstate', function(event){
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) return;
console.log('Popstate');
// By the time popstate has fired, location.pathname has been changed
ajaxLoadPage(location.pathname);
});
});
One improvement you could make to this JS is only to attach the click event handler if the browser supports the history API.
I actually found myself with a similar need today and found the code you provided to be very useful. I came to the same problem you did, and I believe all that you're missing is pushing your index file or home page to the history in the same manner that you are all subsequent pages.
Here is an example of what I did to resolve this (not sure if it's the RIGHT answer, but it's simple and it works!):
var home = 'index.html';
history.pushState({page:home}, null, home);
Hope this helps!
I realize this is an old question, but when trying to manage state easily like this, it might be better to take the following approach:
$(window).on('popstate',function(e){
var state = e.originalEvent.state;
if(state != null){
if(state.hasOwnProperty('window')){
//callback on window
window[state.window].call(window,state);
}
}
});
in this way, you can specify an optional callback function on the state object when adding to history, then when popstate is trigger, this function would be called with the state object as a parameter.
function pushState(title,url,callback)
{
var state = {
Url : url,
Title : title,
};
if(window[callback] && typeof window[callback] === 'function')
{
state.callback = callback;
}
history.pushState(state,state.Title,state.Url);
}
You could easily extend this to suit your needs.
And Finally says:
I'd have thought the browser would be happy to step back to an entry that was created by a normal request.
I found an explanation of that strange browser's behavior here. The explanation is
you should save the state when your site is loaded the first time and thereafter every time it changes state
I tested this - it works.
It means there is no need in loading your content based on window.location.
I hope I don't mislead.

How to deal with page refresh when using HTML5 History?

I have read through tons of tutorials and examples to no avail which leads me to ask my question here. I am developing a webpage with a fixed side navigation with a dynamic content div.
Problem
When i click on a link let's say 'load', the content div will display the content from my other page 'loadcourses.php' then using the history api i will change the url to 'http://mydomain.com/main.php?page=loadcourses'. Basically the main.php will not change i will just add the title of the other page and tag it as a parameter behind the link.
Next, from the dynamically loaded content, i have some links to show the content of each individual course when clicked. The crucial part lies here, once i clicked on any link, i am supposed to parse another parameter to the next page which is 'course.php'. I have set my href='http://mydomain.com/course.php?cid=CSC101'. Now i have no problem loading the first time with the dynamic div loading the content and successfully retrieving the id CSC101 at the next page. But when i hit refresh, my cid is lost.
The back/forward button works fine as per the history api. Help needed here, Thanks!! I am currently working on this .jsp prototype.
document.addEventListener('DOMContentLoaded', init, false);
function hasBrowserHistory(){return !!(window.history && history.pushState);}
function updateHistory(url, replaceHistory) {
//Create a page path
var path = "?page=" + url.split(".")[0];
var object = {
data: url
};
if(replaceHistory){
//alert('as');
/*
If this is the first page we are loading
replace the current history item.
*/
history.replaceState(object, null, path);
}else{
//alert('qw');
/*
If we got here by clicking one of the links
add a new item to the browser history
*/
history.pushState(object, null, path);
}
}
function loadPage(whichPage, replaceHistory) {
$('#contentCol').load(whichPage);
updateHistory(whichPage, replaceHistory);
}
function historyPopStateHandler(e) {
//var state = history.state;
if (e.state == null) {
alert(e.state.url);
}
if(e.state != null) {
loadPage(e.state.data, true);
}
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function init() {
//Check if the history API is available
if(!hasBrowserHistory()){
alert('Sorry dude, your browser does not support the history API');
return;
}
//Check if we have any url params (e.g bookmark or reload)
var params = getUrlVars();
if(params['page'] != undefined && params['page'] != null){
//Load the holder page with the correct content
loadPage(params['page'] + ".jsp", true);
}else{
//Load the default page
loadPage('loadcourses.jsp', true);
}
//Setup listeners for the links
jQuery('nav > a').click(function(e){
e.preventDefault();
loadPage(jQuery(e.target).attr('href'), false);
});
//Setup listeners for the history events
window.addEventListener('popstate', historyPopStateHandler);
}
yea guyz i heard the same problem but i fixed it... its so simple, when you hit refresh, the browser will request the page from the server and the page would not be there...
to cater for this you need a .htaccess file that will be used in redirecting those requests to the respective php file... like if the url is www.you.com/coding, the .htaccess file will scan for the word coding, the redirect the request to coding.php...
inside the php, you need to get the url of the request $_SERVER['REQUEST_URI'] then do some filtering...
if the request satisfy the filters... have a html page embeded on that php
bla..
?>
so in the html put the values that would have appered when you loaded the form... and thats the logic i even tried it in my website deenze and it worked

Categories

Resources