`window.location.reload` doesn't reload page in Chrome - ajax

I am using following code to let the user log into Magneto with AJAX. If the correct username and password is entered the page will refresh and display the user navbar in the header. The field works in Firefox, Safari and IE but not in Chrome. I have to refresh the page for the navbar to display.
Why does this problem occur?
Code:
AjaxLoginForm.submit = function(button){
if (this.validator.validate()) {
// show ajax image
// button.insert({"after":osc_ajax_loading_small});
AjaxLoginForm.hideLoader();
AjaxLoginForm.insertLoader(button);
$("ajaxlogin_form").request({
onSuccess: function(transport) {
var json = transport.responseText.evalJSON();
if(json.is_forgot_pwd){
if(json.success){
$("ajaxlogin_form_message").update("<div>"+json.success_message+"</div>");
$("ajaxlogin_form_message").show();
}
if(json.error){
$("ajaxlogin_form_message").update("<div>"+json.error_message+"</div>");
$("ajaxlogin_form_message").show();
}
}else{
if(json.success){
// If the correct username and password is entered
// the page will refresh and display user navbar
// in the header
window.location.reload();
}
if(json.error){
$("ajaxlogin_form_message").update("<div>"+json.error_message+"</div>");
$("ajaxlogin_form_message").show();
}
}
AjaxLoginForm.hideLoader();
//setTimeout("AjaxLoginForm.hideResponseMessage()", 5000);
}
});
}
}.bind(AjaxLoginForm);

You can try it with a setTimeout.Also you can simplify the code,currently you are writting json.success and json.error multiple times which should be written once.
setTimeout(function(){
window.location.reload();
},100);

try this, I am preety sure in chrome window.location = self.location; should work, or try location.reload( true ); otherwise by callback some other function to reload your page.
Otherwise you should get some error that prevents reload, you can get a console in success.

For script is in iframe top.location.reload() works for me.

Related

logout and click back takes me to authenticated pages in Safari browser [duplicate]

Got an issue with safari loading old youtube videos when back button is clicked. I have tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.
Is there any way to prevent safari loading from cache on a certain page?
Your problem is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.
When page is loaded for bfcache onload event wont be triggered. Instead you can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache it is set to true.
Kludgish solution is to force a reload when page is loaded from bfcache.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
If you are using jQuery then do:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
All of those answer are a bit of the hack. In modern browsers (safari) only on onpageshow solution work,
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
but on slow devices sometimes you will see for a split second previous cached view before it will be reloaded. Proper way to deal with this problem is to set properly Cache-Control on the server response to one bellow
'Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'
Yes the Safari browser does not handle back/foreward button cache the same like Firefox and Chrome does. Specially iframes like vimeo or youtube videos are cached hardly although there is a new iframe.src.
I found three ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1
1. Detect if user is using the back/foreward button, then reload whole page or reload only the cached iframes by replacing the src
if (!!window.performance && window.performance.navigation.type === 2) {
// value 2 means "The page was accessed by navigating into the history"
console.log('Reloading');
//window.location.reload(); // reload whole page
$('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
}
2. reload whole page if page is cached
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
3. remove the page from history so users can't visit the page again by back/forward buttons
$(function () {
//replace() does not keep the originating page in the session history,
document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
});
You can use an anchor, and watch the value of the document's location href;
Start off with http://acme.co/, append something to the location, like '#b';
So, now your URL is http://acme.co/#b, when a person hits the back button, it goes back to http://acme.co, and the interval check function sees the lack of the hash tag we set, clears the interval, and loads the referring URL with a time-stamp appended to it.
There are some side-effects, but I'll leave you to figure those out ;)
<script>
document.location.hash = "#b";
var referrer = document.referrer;
// setup an interval to watch for the removal of the hash tag
var hashcheck = setInterval(function(){
if(document.location.hash!="#b") {
// clear the interval
clearInterval(hashCheck);
var ticks = new Date().getTime();
// load the referring page with a timestamp at the end to avoid caching
document.location.href.replace(referrer+'?'+ticks);
}
},100);
</script>
This is untested but it should work with minimal tweaking.
The behavior is related to Safari's Back/Forward cache. You can learn about it on the relevant Apple documentation: http://web.archive.org/web/20070612072521/http://developer.apple.com/internet/safari/faq.html#anchor5
Apple's own fix suggestion is to add an empty iframe on your page:
<iframe style="height:0px;width:0px;visibility:hidden" src="about:blank">
this frame prevents back forward cache
</iframe>
(The previous accepted answer seems valid too, just wanted to chip in documentation and another potential fix)
I had the same issue with using 3 different anchor links to the next page. When coming back from the next page and choosing a different anchor the link did not change.
so I had
House 1
View House 2
View House 3
Changed to
House 1
View House 2
View House 3
Also used for safety:
// Javascript
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
// JQuery
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
None of the solutions found online to unload, reload and reload(true) singularily didn't work. Hope this helps someone with the same situation.
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
jQuery(document).ready(function()
{
var d = new Date();
d = d.getTime();
if (jQuery('#reloadValue').val().length == 0)
{
jQuery('#reloadValue').val(d);
jQuery('body').show();
}
else
{
jQuery('#reloadValue').val('');
location.reload();
}
});
There are many ways to disable the bfcache. The easiest one is to set an 'unload' handler. I think it was a huge mistake to make 'unload' and 'beforeunload' handlers disable the bfcache, but that's what they did (if you want to have one of those handlers and still make the bfcache work, you can remove the beforeunload handler inside the beforeunload handler).
window.addEventListener('unload', function() {})
Read more here:
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching

How to make sure page loads completely in cypress

I am working in cypress.
Steps to repro
I just visit the login page by cy.visit()-spinner is loading
passed the credentials using type-spinner is still loading
click on submit.-spinner is still loading
its throwing error .. why because the login page XHR calls didnt get completed thats why still we can see spinner loading in top and i tried to click the submit button before it gets loaded,may be because of poor network-telling invalid credentials.
I believe you have to wait for the XHR request to get completed and validate the page load or perform other actions.
Here is a sample,
// Wait for the route aliased as 'getAccount' to respond
cy.server()
cy.route('/accounts/*').as('getAccount')
cy.visit('/accounts/123')
cy.wait('#getAccount').then((xhr) => {
cy.get('#loading-bar').should('not.be.visible')
})
Here is a similar solution which I have previously given - Cypress:Is there any way to check invisibility of an element
You check if the button is present and then click on the button.If
describe('check if button present', function () {
it('check for button using CSS Selector', function () {
cy.visit(url)
let found = false
let count=0
while (!found) {
const nonExistent = Cypress.$('.btn-selector')
if (!nonExistent.length) {
found = false
count=count+1
cy.wait(1000)
if(count==60)
{
found = true
cy.log('Element not found after 60 seconds..Exit from loop!!!')
}
}
else
{
found = true
cy.get('.btn-selector').click()
}
}
})
})

cannot click links contained within ajax response

I have some content returned via ajax, and that content contains some links, but if I click them nothing happens (they don't respond to the JS written for them). Then, If i refresh the page, the first time I click, it works, and then it doesn't again.
How can I make it work normally?
This is basically my ajax call:
$('a.add').click(function() {
var data = {
action: 'ADD_PROD'
};
// make the request
$.get(ajax_object.ajax_url, data, function(response) {
// $('#vru_div').html(data);
$('div.left').html(response);
});
// $('div.left').html('<img src=712.gif>');
// alert('code');
return false;
});
The new links won't have any event handlers attached to them.
try using
$('.left').on('click','a',function(){
//your logic
});

How to open new page without refresh

I am using a rails application, in which I am trying to open a new page, all the static page, https://www.mazzey.com/ is the link, if you click on the header buttons, it opens new page with fade in and fade out effect with the header and footer without refreshing in Mozilla Firefox but in Google Chrome the header also refreshes. I also found that that header and footer refreshes in Firefox as well but it does not that unlike Google Chrome. So can I use to Ajax or any plugin to do that to avoid refresh of header and footer ?
$(function(){
var newHash = '',
$mainContent = $("#main-content");
$(".nav").delegate("a","click",function(){
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange',function(){
newHash = window.location.hash.substring(1);
if(newHash){
$mainContent.find("#guts").fadeOut('slow',function(){
$mainContent.hide().load(newHash + " #guts",function(){
$mainContent.fadeIn('slow');
});
});
}
});
$(window).trigger("hashchange");
});
This what I am using with the ba-hashchange plugin
for more information check this
css-tricks.com/video-screencasts/85-best-practices-dynamic-content/

Ajax loading element into page

Trying to load contents from an element into another element from another page, problem is in chrome it loads the entire page in to the element. See for yourself here: http://www.monsterhighshop.co.uk/gadgets-electonics
$(function(){
e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
$("a[rel='sort']").click(function(e){
pageurl = $(this).attr('href')+"?rel=sort #categoryproducts-productlisting";
$('#categoryproducts-productlisting').load(pageurl);
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=sort',success: function(data){
$('#categoryproducts-productlisting').html(data);
}});
});

Resources