Unexpected web page refresh in Chrome browser - javascript

I've been facing this weird behavior for a while now and can't find any workaround.
There is a button with certain methods called on click.
In Firefox works well. In Chrome it just refreshes the whole page.
$("#modoComparativa").click(function(){
if($(this).hasClass("active")){
$('#histFromDate').attr("placeholder","Date 1");
$('#histToDate').attr("disabled","disabled").attr("placeholder","Date 2");
startDatepickerComp();
}
else{
$('#histFromDate').attr("placeholder","Initial date");
$('#histToDate').attr("disabled","disabled").attr("placeholder","Final date");
startDatepicker();
}
$('#clearDates').attr("disabled","disabled");
// This function calls another function causing the odd behavior in Chrome
requestGraph(idDetail, idArea, "", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If I comment out everything but the selector and the call to the click method, the behavior is the same. It refreshes everything.
I can't figure out how to debug this as each time I press the button, the whole page refreshes and no log/errors remains in the browser debugger.
Any ideas would be appreciated.
Edit - Addition of the selector as requested:
<div class="form-group"><button class="tooltip3 btn btn-default glyphicon glyphicon-random" id="modoComparativa" data-toggle="tooltip" title="ACTIVAR COMPARATIVAS" data-placement="bottom"></button>
</div>

Add a return false to your click callback to prevent actions due to your html syntax (like form submission or clicking on a anchor tag).
$("#modoComparativa").click(function(event){
event.preventDefault();
// your existing code
}
Edit: Since you added your html...
If your button is within a form, you can also add the type="button" attribute to prevent it from submitting your form.
<button type="button" class="tooltip3 btn btn-default glyphicon glyphicon-random" id="modoComparativa" data-toggle="tooltip" title="ACTIVAR COMPARATIVAS" data-placement="bottom"></button>
Thank you to lonesomeday for suggesting http://api.jquery.com/event.preventDefault/

I added an answer which could be useful for people stumbling here but having other causes for this behavior.
This kind of unexpected random reload can be due to several causes:
As stated in other answers a link which propagates the click and then performs a GET on the page itself
An image tag <img> where the src is empty or invalid, the browser will attempt to load the image using GET, but will in fact refresh the page instead (empty = relative to the page = page). Even a hidden image will be loaded, so this can be tricky to find, use the browser console !
Some javascript logic which refreshes the page programmatically in some conditions (session expired, token expired ...)
A browser 'feature', for example: https://support.mozilla.org/en-US/questions/1204335, or https://superuser.com/questions/1048029/disable-auto-refresh-tabs-in-chrome-desktop
In any case use the browser console and look for suspect GET calls to the page itself or redirects.

Related

How can I get elements inner text after dom is being refreshed after the submit button?

I'm working on automating a task (filling a form and submitting data then getting the result message where the data is being read from a txt file line by line).
While running my JS code via the console, everything works fine until before the clicking on submit button. after the click on the submit button, I can see the HTML is being reloaded with new data and the URL is changed from www.example.com to www.example.com/requests/12345 and then the next step after the click is not respected.
I thought may be because I was using:
document.getElementByID("btn-submit").click();
and changed it to
$("#btn-submit").click().trigger('change');
But still same issue.
I tried to use sleep functions and setTimeout to wait for the new HTML to load but this didn't help at all :(
The task is simple steps until button click all works perfect, I'm stuck only at after the submit button as I want to get the results that shows on the page after clicking the submit button.
Any ideas please what is being done wrong from my side?
The Elements I'm trying to get are in a div that is empty before the submit button is being clicked like this
<div id="message-bar">
</div>
After the submit button is clicked it is filled like the below (also the URL is changed to something link www.example.com/requests/12345 - of course the result elements won't show if the button is not clicked:
<div id="message-bar">
<div id="alert-success" class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<div class="text alert-text">Request approved!</div>
<ul id="bullet-items"><li>Thank you</li></ul>
</div>
</div>
I tried to check if the element is not empty, then get the elements innerText, but seems like my code is being removed when the page URL changes after the submit button:
if (document.getElementById("message-bar").innerText != "") {
// do something
}
Thank you so much
Try
$("#btn-submit").click(function(event){
event.preventDefault();
})
Or without jQuery
var btn = document.getElementById('btn-submit');
btn.addEventListener('click',function(event){
event.preventDefault();
})
Try using the .preventDefault() event
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault).
From what I understand you need the content not after the click, but after what the click is triggering. Here’s the same Q, answered. Basically you wait for the mods to happen then “read” the element content.
to fix my issue, I thought of using window.open("URL") by creating a variable for it and then using it to process my the whole automation process on the new window and I was able to get all the result message from the new window
var newWindow = window.open("the URL");
newWindow.$('input[id="input"]').val("1234").trigger('change');
etc...

JavaScript code on onClick event causing "dangerous Request.Path" error

I am attempting to expand a CMS system we are using ... writing HTML code to create a Button with the onClick event calling a custom JavaScript function defined.
The function that is being called first queries the user with a "confirm()", and if the user clicks OK then it performs a window.location redirect; if the user clicks CANCEL then the method does nothing.
The redirection ultimately happens, however, in BOTH cases an error appears. In the case selecting OK, because of the redirect, the error that is displayed is short-lived (however the error still happens). In the case of selecting the CANCEL button, at the bottom of my page is get the following error: "There was an error with the form. Please contact the administrator or check logs for more info."
I checked all logs I could find and no further details could be found. I turned "customErrors" off and when viewing the actions performed in Chrome's DevTools environment I see the following: "A potentially dangerous Request.Path value was detected from the client (:)"
I have no clue why I am seeing this error ... I am also pasting my button code below. Any suggestions?
P.S. Running Bootstrap v3
function jsDeleteFileID(p_intFileID)
{
var objAnswer = confirm("Are you sure you want to delete this file?");
if (objAnswer == true)
{
//****************************************
// Reload Page w/ Parameters
//****************************************
location.href='http://www.MyRedactedWebsiteDomain.com/RedactedWebpageName?DFID=' + p_intFileID + '&ReturnURLID=AAA-AAA-AAA-AAA';
}
else
{
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button"
data-loading-text="Please wait..."
data-name="DeleteFile152"
class="btn submit form-button af-btn-loading btn-normal btn-danger"
id="dnn111DeleteFile152"
onClick="jsDeleteFileID(152); return false;"
<i class="glyphicon glyphicon-trash"></i> Delete
</button>
After posting the above, I figured out what the problem was. I would like to post my solution here in case anyone else that is programming on DotNetNuke and using DNNSharp Modules has the same issue.
The problem was in the labels listed in the class property. I removed two class labels: "submit", and "form-button". These two classes added some sort of additional processing that ran AFTER my custom java code which caused errors. Since I only want my code to run and nothing else, removing these two class labels stopped that extra code from running, and now my button behaves as expected.

Page reloads when clicking anchor element

I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:

problem with javascript: return false is not working

Hey there is a link in my program as shown and onclick it calls the function clearform as shown:
Html Code:
<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm()">Cancel</a>
JavaScript Code:
function clearForm(){
document.getElementById("subjectName").value = "";
return false;
}
return false is not working in this code. actually the first line of the function executed successfully but the return false was failed. I mean page is redirected to url "Cancel".
Change your code as
<a class="button" href="Cancel" onclick="return clearForm()">Cancel</a>
Your problem is you need to return the Boolean.
But, drop all that...
Attach your event unobtrusively...
element.onclick = clearForm;
Use preventDefault(). It is the modern way of acheiving that.
function clearForm(event) {
event.preventDefault();
}
<a class="button" href="Cancel" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>
should work
Please note that if there is a bug or error in clearForm() then "return false" will NOT stop the anchor action and your browser will try to link to the href "Cancel". Here is the logic:
User clicks on anchor
onClick fires clearForm()
There is an error in clearForm() so Javascript crashes and stops all code execution.
return false is never fired because Javascript has already stopped.
If you are relying on a third party JavaScript API (I was using code supplied by Recyclebank to spawn a popup), and the third party API makes an update that breaks the JavaScript, then you'll have problems.
The following will stop the link under normal conditions and error conditions.
<a class="button" href="javascript:;" style="left: 55%;" onclick="clearForm();return false;">Cancel</a>
The return false; somehow needs to be right at the front.
(In ALL situations I've dealt with over the past months - may or may not be a bug).
Like this: onclick="return false; clearForm();"
Besides that, as mentioned by others as well, you need to return it from the onclick, not just from the function.
In your case: onclick="return clearForm()".
Keep in mind that some browser extensions may interfere with proper operation of links. For example, I ran into a situation where someone had both AdBlock Plus and Ghostery enabled. Clicking a simple 'a' tag with an 'onclick="return SomeFunction();"' attribute (the function returned false) caused the browser to treat the click as a page transition and went to a blank page and the loading indicator just kept spinning. Disabling those browser extensions cleared up the problem.
Including this as an answer because this was the first page I landed on from Google.

.text & .attr in Jquery not working in IE

I am having some trouble getting a function to work in internet explorer (7-8). My problem is that I need to hide some links until a user logs in, I would do this server side; however, suffice to say I have no way of doing this.
My approach has been to load a set of text (login/logout) that will change server side and test for the logout value. I was doing this by loading a div by id in Jquery and using the .text() when IE 7-8 both refuse to run this ie dev tools told me that "object doesn't support this property or method" with a reference back to the line of code containing this lookup. Code posted below:
function logintest(){
login_test= "Sign out";
alert($('#log').text());
login = $('#log').text();
if(login.search(login_test) == -1){
$('#hiddenBox').css('display','none');
}
};
The fun thing is that the alert runs properly and displays the right text string. Upon this failing I tried using the .attr() and got identical results. Any help would be great!
Jquery version: 1.4.4
Site: www.brainwellnesspro.com
IE: 7-8 on win xp
Looking at your site I'd start by fixing the html to be valid, this isn't good:
<div id="log" name="<a href='http://www.brainwellnesspro.com/login.php' onclick=''>Sign in</a> or <a href='http://www.brainwellnesspro.com/login.php?action=create_account' onclick=''>Create an account</a>">
<a href='http://www.brainwellnesspro.com/login.php' onclick=''>Sign in</a> or <a href='http://www.brainwellnesspro.com/login.php?action=create_account' onclick=''>Create an account</a>
</div>
and since you already have jquery you can check the current text value of the login link like this
function logintest(){
if($("#log a").first().text() !== "Sign out"){
$('#hiddenBox').css('display','none');
}
};
My problem is that I need to hide some
links until a user logs in, I would do
this server side; however, suffice to
say I have no way of doing this.
Why Not? Surely your application should know if the user is logged in or not (and be able to render differently accordingly?)
anyway - without seeing your markup (with the context of the element with id='log' (what type of element is this???)....
if(login.search(login_test) == -1)
should probably be
if(login.search(login_test) == '-1')

Categories