Javascript: Why sometimes alert() does not work but console.log() does? - javascript

From time to time, I face a very intriguing bug. My javascript code does not display an alert(msg) during execution, but if I use a console.log(msg) it does show up in the console. What could prevent alert() from displaying?
Thanks a lot

This is a very common problem, and everyone has faced this problem atleast once.
The reason alert() does not work is because previously you have checked "prevent this page from creating additional dialoug" checkbox.
lets take a look at this code.
<script type="text/javascript">
var js_name = ['elem1', 'elem2']
for (var i = 0; i < js_name.length; i++) {
alert(js_name[i]);
};
</script>
There will be two alert boxes if you run the code. If you check the "prevent this page from creating additional dialoug" checkbox and then refresh the page again you won't get alert box ever again.
Solution is you need to close that webpage and reopen again in the browser(don't need to close the entire browser).
I am assuming you are using chrome.
Internet Explorer or FireFox doesn't have this checkbox feature.

If you override alert function so it won't work
alert = function()
{
...
};
alert('hello') // won't show any alert

To my knowledge alert() is always shown unless it is repetitive in which case you are asked if you want to continue showing alerts.
I suppose the specifics on how this is handled depends on your browser. Care to share any more details? :)

This also happens in ColdFusion. If you use anywhere after the script tag a cflocation tag (instead of location.href) the alert will not show.

This can also happen in Firefox if you have Dev Tools open and Responsive Design Mode enabled. It sounds like it's a bug.

In Firefox: go to Options -> Content and uncheck "block pop-up windows" check box. Restart browser.

Another reason why alert, confirm, and prompt may be ignored by the browser, is if the document is in an iframe that has a sandbox-attribute without allow-modals in its value.
For example, Firefox silently ignores this, however Chromium shows a warning.

If you try to execute javascript alert function in a Chrome browser address URL, you will not get the message if the the tab has no page previously loaded.
You will get the alert box only if it is not a fresh tab.
If there exists a web page that is previously loaded, and then you try to run the javascript in the address bar, you will get the expected result.
Hope it clarifies this difficult to detect behavior in Chrome.

If you have a location.reload() after the alert() function as shown below, JavaScript somehow skips the alert and reloads the page.
$.ajax({
url:'xxx',
type : 'POST',
data : datavalues,
dataType: 'json',
contentType: 'application/json',
success: function(response){
if(response.status == '200')
{
alert("updated");
}
}
});
location.reload();
To tackle this situation, I moved the reload function into the if block and this solved the issue.
$.ajax({
url:'xxx',
type : 'POST',
data : datavalues,
dataType: 'json',
contentType: 'application/json',
success: function(response){
if(response.status == '200')
{
alert("updated");
location.reload();
}
}
});

I have a similar problem here, when I replace the console log with "alert" it is not working but console.log does work.
The not working code is :
request(options, function(error, response, body) { // Requesting API
var statusCode = response.statusCode;
if(statusCode === 200){
alert("Success");
} else {
alert(error);
}
and the working code is:
request(options, function(error, response, body) { // Requesting API
var statusCode = response.statusCode;
if(statusCode === 200){
console.log("Success");
} else {
console.log(error);
}

Related

jQuery check if a file exist locally

I am developing a local site for a company (only local internal use, offline and without server). I have a main page that has a main div, that contain 3 different div. Each div is linked to a page and the "onclick" event of each div will load the page linked into the main div. So i have to check, with the document ready function, if each page exists and, if not, I want to delete the div linked to that page. How can I check if a page exist locally? I've found many answere that check with status of connection if a page exists, but my html will only work offline and locally, so I can't use that method.
EDIT - SOLVED
I've solved this using the script of #che-azeh:
function checkIfFileLoaded(fileName) {
$.get(fileName, function(data, textStatus) {
if (textStatus == "success") {
// execute a success code
console.log("file loaded!");
}
});
}
If the file was successfully load, i'd change the content of a new hidden div that will tell to another script if it have to remove or not each of the three div.
This function checks if a file can load successfully. You can use it to try loading your local files:
function checkIfFileLoaded(fileName) {
$.get(fileName, function(data, textStatus) {
if (textStatus == "success") {
// execute a success code
console.log("file loaded!");
}
});
}
checkIfFileLoaded("test.html");
I suggest you run a local web server on the client's computer. (See also edit below on local XHR access).
With a local web server they can start it up as if it was an application. You could for example use node's http-server. You could even install it as an node/npm package, which makes deployment also easier.
By using a proper http server (locally in your case) you can use xhr requests:
$(function(){
$.ajax({
type: "HEAD",
async: true,
url: "http://localhost:7171/myapp/somefile.html"
}).done(function(){
console.log("found");
}).fail(function () {
console.log("not found");
})
})
EDIT:
Firefox
Another post has (#che-azeh) has brought to my attention that firefox does allow XHR on the file "protocol". At the time of this writing the above works in firefox using a url of just somefile.html and using the file scheme.
Chrome
Chrome has an option allow-file-access-from-files (http://www.chrome-allow-file-access-from-file.com/). This also allows local XHR request
This flag is intended for testing purposes:
you should be able to run your tests in Google Chrome with no hassles
I would still suggest the local web server as this make you independent of these browser flags plus protect you from regression once firefox/chrome decide to disable support for this.
You can attempt to load the page within a try-catch construct. If the page exists, it will be loaded though. If it doesn't, you can (within the catch) set the related div as hidden.
Try to access the page using $.ajax. Use the error: option to run a callback function that removes the DIV linked to the page.
$.ajax({
url: "page1.html",
error: function() {
$("#page1_div").remove();
});
You can loop this code over all the DIVs.
You can use jquery load function
$("div").load("/test.html", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$(this).html(msg + xhr.status + " " + xhr.statusText);
}
});

Ajax method does not fire on initial page load

Note: Please see edit at the bottom after reading this question.
This issue is only happening in IE 11, and only started occurring after a recent Windows update. There were 5 updates, one of which was specific to IE, so I uninstalled that one. However, the issue still exists. Before I consider rolling back the remaining updates, is there something inherently wrong in my code? The following is inside the document ready function:
$('#leftmenu>li').click(function () {
var clickedId = this.id;
$.ajax({
url: "Session/Index/",
cache: false,
success: function (result) {
if (result.length > 0)
{
performListItemAction(clickedId);
}
else
{
window.location.href = 'Home/Index/'
}
}
});
});
And the following is the performListItemAction method (a separate function not in document.ready):
function performListItemAction(item)
{
alert("clicked");
$(".tabui").each(function ()
{
$(this).hide();
});
$(".listitem").each(function ()
{
$(this).css("background", "transparent");
});
$(document.getElementById(item)).css("background-color", "#C8C8C8");
var targetId = $(document.getElementById(item)).data('target');
var target = $(document.getElementById(targetId));
target.show();
}
The alert clicked never appears when this problem happens, and that is how I concluded the ajax call is not working.
A few other notes:
This issue isn't happening on Firefox.
This only happens if I directly login to the page with a direct URL. If I log in via the application's home screen, and then go to the page that uses the above javascript, the issue doesn't occur.
Thank you.
EDIT: I just now see that the same issue is now occurring in Firefox as well. It's just much less frequent.
After trial and error, I think I fixed the issue by adding a forward slash to the beginning of each of the URLs, and added the type: "POST", to the ajax call. I don't know why it was working fine before, but now this works in all my attempts.

Internet Explorer issues running code if debugger closed

Yesterday I encountered an interesting issue with Internet Explorer. A script runs perfectly on Chrome, Firefox, Safari, but with Internet Explorer 11 it doesn't do anything. If I open the debugger it runs smoothly and everything is as it should, but the moment I close the debugger it stops working and I have no idea why is this. My first thought was the IE extensions, but I disabled them to no veil. I tried running in safe-mode, with admin rights, but nothing seems to work.
To summarize everything: IE - script runs ONLY while the debugger is On. No error is produced, it just doesn't work.
I would be really glad for any ideas what can I do regarding this. Thank you in advance.
--------------EDIT---------------
Here is the script that doesn't run.
for (var i = 0; i < AllStrategyGrids.length; i++) {
try {
isChange = true;
var data = $("#objectives").data("kendoGrid").select().data();
if (AllStrategyGrids[i].ID == data.uid) {
var jsonData = new Object();
jsonData.StrategicID = "1";
jsonData.ObjectiveID = $("#ObjectiveID").val();
jsonData.HeaderID = "00000000-0000-0000-0000-000000000000";
jsonData.PeriodID = "00000000-0000-0000-0000-000000000000";
jsonData.Strategic = "Please enter strategic";
jsonData.TaskStatus = "";
jsonData.TaskStatusID = "1";
jsonData.Position = "";
jsonData.Sorted = "1";
jsonData.SessionID = "00000000-0000-0000-0000-000000000000";
tmpGrid = AllStrategyGrids[i].Grid.data("kendoGrid");
var dataRows = tmpGrid.items();
var rowIndex = dataRows.index(tmpGrid.select());
$.ajax({
url: "CreateStrategy",
type: 'POST',
data:
{
strategics: jsonData,
VersionID: $("#VersionUID").val(),
index: rowIndex
},
success: function () {
tmpGrid.dataSource.read();
}
});
}
} catch (e) { }
}
Just a guess, this is likely because you have a console.log in that script and in IE the console object doesn't exist if your debugger is closed... we've all be there :)
An easy fix is the just add small shim as early on in your site as you can.. it won't do a thing on any browsers except IE and will just stop the execution error that probably blocking your other JS code from running...
<script>
if(!console)console={log:function(){}};
</script>
a more robust solution here :
'console' is undefined error for Internet Explorer
---- EDIT
Okay one thing i can see from your code is that you're going to fail silently because you've used a try catch but do nothing with it. This is going to catch any exception you are having (blocking it from reaching your window thus making it seem like you have no errors). I would perhaps alert the error message at the very least while testing (so you don't need to open Debugger) and see if anything is thrown...
I'd be suspecting your ajax request myself.. that or an undefined in IE8.. so add some logging alerts (brute force i know) to test your assumptions at certain points e.g.
alert("Reach here and data="+data);
Alternatively, i can also see that your ajax request has no callbacks for unsuccessful which might be good idea to add to your call. It might be that the success isn't calling for some reason...
$.ajax({
url: "CreateStrategy",
type: 'POST',
data:
{
strategics: jsonData,
VersionID: $("#VersionUID").val(),
index: rowIndex
},
success: function () {
tmpGrid.dataSource.read();
}
})
.fail(function() {
alert( "error" );
//handle a failed load gracefully here
})
.always(function() {
alert( "complete" );
//useful for any clean up code here
});
Final food for thought.
Since you're checking the DOM for an item, and i have no idea when this code is called but just in case its called directly AFTER a page reload..and lets assume something in IE isn't ready at 'that' point, it might be the DOM isn't ready to be queried yet? Try executing this code when the DOM is ready.. lots of ways to achieve this $.ready , setTimeout(f(){},1) or vanilla... but you get the idea..
Note: Debugging Script with the Developer Tools: MSDN
To enable script debugging for all instances of Internet Explorer, on
the Internet Options menu, click the Advanced tab. Then, under the
Browsing category, uncheck the Disable script debugging (Internet
Explorer) option, and then click OK. For the changes to take effect,
close all instances of Internet Explorer then reopen them again.

Chrome window.open after ajax request acts like popup

I have a situation where, when a user pushes a button I perform an ajax request, and then use the result of the ajax request to generate a URL which I want to open in a new tab. However, in chrome when I call window.open in the success handler for the ajax request, it opens in a new window like a popup (and is blocked by popup-blockers). My guess is that since the the success code is asynchronous from the click handling code that chrome thinks it wasn't triggered by a click, even though it is causally related to a click. Is there any way to prevent this without making the ajax request synchronous?
EDIT
Here is some minimal code that demonstrates this behaviour:
$('#myButton').click(function() {
$.ajax({
type: 'POST',
url: '/echo/json/',
data: {'json': JSON.stringify({
url:'http://google.com'})},
success: function(data) {
window.open(data.url,'_blank');
}
});
});
http://jsfiddle.net/ESMUA/2/
One note of clarification: I am more conerned about it opening in a separate window rather than a tab, than I am about it being blocked by a popup blocker.
Try to add
window.open(url,'_blank');
Edit
Well, I don't think you can get around popup-blockers when opening a page that's not the immediate result of a user action (i.e. not async).
You could try something like this though, it should look like a user action to a popup-blocker:
var $a = $('<a>', {
href: url,
target: '_blank'
});
$(document.body).append($a);
$a.click();
Edit 2
Looks like you're better of keeping things sync.
As long as the new window is "same origin" you have some power to manipulate it with JS.
$('#a').on('click', function(e){
e.preventDefault();
var wi = window.open('about:blank', '_blank');
setTimeout(function(){ // async
wi.location.href = 'http://google.com';
}, 500);
});
Try adding async: false. It should be working
$('#myButton').click(function() {
$.ajax({
type: 'POST',
async: false,
url: '/echo/json/',
data: {'json': JSON.stringify({
url:'http://google.com'})},
success: function(data) {
window.open(data.url,'_blank');
}
});
});
What worked for me was:
var win = window.open('about:blank', '_blank');
myrepository.postmethod('myserviceurl', myArgs)
.then(function(result) {
win.location.href = 'http://yourtargetlocation.com/dir/page';
});
You open the new window tab before the sync call while you're still in scope, grab the window handle, and then re-navigate once you receive the ajax results in the promise.
The answer posted by #pstenstrm above (Edit 2) mostly works, but I added just one line to it to make the solution more elegant. The ajax call in my case was taking more than a second and the user facing a blank page posed a problem. The good thing is that there is a way to put HTML content in the new window that we've just created.
e.g:
$('#a').on('click', function(e){
e.preventDefault();
var wi = window.open('about:blank', '_blank');
$(wi.document.body).html("<p>Please wait while you are being redirected...</p>");
setTimeout(function(){ // async
wi.location.href = 'http://google.com';
}, 500);
});
This fills the new tab with the text "Please wait while you are being redirected..." which seems more elegant than the user looking at a blank page for a second. I wanted to post this as the comment but don't have enough reputation.
There is no reliable way. If your tab/window has been blocked by a pop-blocker in FF and IE6 SP2 then window.open will return the value null.
https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ
How can I tell when my window was blocked by a popup blocker? With the
built-in popup blockers of Mozilla/Firefox and Internet Explorer 6
SP2, you have to check the return value of window.open(): it will be
null if the window wasn't allowed to open. However, for most other
popup blockers, there is no reliable way.

Browser Window close detection

This is something that's been driving me nuts.
I'm trying to detect whether the uses closes or navigates away from a page in order to do an ajax response upon the event. I have tried almost every possible method to invoke this but no luck. The only thing I can think of is that the activate window in question was fired using: window.open() method. Could that cause any issues? What I have so far:
window.onbeforeunload = function() {
//ajax stuff here
};
However, I've noticed that this does not work after the page is fully loaded. The event fires within the first few milliseconds (if I open the window and try to close it right away) during the page load and won't work after that.
Any ideas?
I once ran into this issue, and found it worked for me only by setting async : false on the ajax, like this:
jQuery(window).bind('beforeunload', function () {
jQuery.ajax({
url: 'your.url',
async: false,
data: yourdata
timeout: 2000 // or whatever timeout in milliseconds you want
success: function(data){
// Do whatever you want
}
});
});
As Ian mentioned on the comments, it's a good idea to set a timeout to prevent the window for taking too long to close in case the request takes a while. And keep in mind it won't work in all browsers...
This also supports old versions of IE and Firefox.
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};

Categories

Resources