Javascript errors effect on browsers - javascript

I provide some additional services to websites that add my script to their site. Technically my script does not interact with actual functionality of the site, the most is does is read some information and the main part of the code only runs only after the event (think something like Google Analytics).
Recently a bug caused an "X is undefined" error to occur in some circumstances and the client insists that this error is crashing their site. They sent me a screenshot that shows a blank page and a console screenshot that shows the error but they removed my code so I was not able to see it in real time.
My question is if there is any possibility that these types of errors can affect the website. For example assume this code runs on the website:
var tmp = Sizzle('h1');
tmp[0].innerHTML = "test";
Assume that for some reason Sizzle is not defined when the code runs or that there weren't any H1 elements on the page so tmp is empty. Could the resulting error under any circumstances affect the outside environment. e.g the page the code runs on? Obviously if I had overwritten the body element then yes it will affect the website but my question is only about "x is undefined" or syntax errors.

An Error will break the execution of the current function-stack.
For example if you have a onclick event, that calls a function and you have an error at the beginning it will not execute anything after that code. But that doesn't mean that any JavaScript on your Website won't work anymore. Everything will still be fine and run. Of cause if there was something important that was not executed after an Error it would change the logic of your runtime.
You can also avoid Error to go down the function-stack with a try-catch block:
function a() {
var x = new DoesNotExist()
alert("test a") // this will not alert() as there is an error before
}
function b() {
try {
var x = new DoesNotExist()
} catch (e) {}
alert("test b") // this will alert because the error is catched
}
alert("code is running")
a()
b() // this will not execute as a() broke this script
// however pressing the button b will still alert in b() as it's in a new stack
alert("code finished")
<input onclick="a()" value="a" type="button" />
<input onclick="b()" value="b" type="button" />

Yes, there are circumstances that error of the type "X is undefined" affects the whole website.
If the code which produces "X is undefined" error is:
inside a function or inside an object method - it will stop this current function from execution but likely will proceed with the script below it.
written as a row by row Javascript statements it will stop on this current point and won't proceed with else script.
Probably your client has more Javascript statements (loading content of the page) below the crashing pont, these statements are not executed and the content is not loaded.
You can simply add to your script:
if (typeof variable !== 'undefined')
{
// else part of the code
}

As JavaScript is a scripting language which alters the DOM and provides user interaction I'd say: in general as long as you do not interfere with the site's content it will not affect the page being loaded. There are two possibilities I could imagine stopping the page from showing up:
your javascript lead to a infinite loop and therefore blocks the content being loaded (but they should have gotten an error like the page not reacting)
the depend the building of their page on stuff they intended to do using your code so it will not load because it doesn't have your code

Related

Javascript try catch statement

I'm analyzing some code on a website and I came across the following anonymous function followed by a try catch statement. I'm just wondering what the try catch statement is doing at the end there. Is it pre-loading the url so thats it loads more quickly then the anonymous function goes? Also, whats the point is it's not catching any errors.
(function() {
var fired = false;
bsnPop.add("http://www.someurl.com", {
under: !noPopunder,
newTab: false,
forceUnder: true,
shouldFire: function() {
return !fired;
},
cookieExpires: -1,
afterOpen: function(url) {
createCookie();
fired = true;
doSecondPop();
}
});
})();
try {
var hint = document.createElement("link");
hint.rel = "dns-prefetch";
hint.href = "http://www.someurl.com";
document.head.appendChild(hint);
var hint = document.createElement("link");
hint.rel = "preconnect";
hint.href = "http://www.someurl.com";
document.head.appendChild(hint);
} catch (e) {}
With reference to the link types list on MDN, "dns-prefetch" and "preconnect" are listed as experimental. They do not appear in the list of "rel" values for link types of link elements in HTML5
So the code is using experimental technology on the web which might throw an error in some browsers. To prevent stopping the application and logging an exception on the console, the code is placed in a try block with a catch block that ignores the error.
In answer to question details, the anonymous function in the IIFE is invoked and passes an object containing parameters and callbacks in a call to bsnPop.add. It does not appear to create a popup window at this stage.
Next code within the try block attempts to speed up access to the web site by requesting DNS lookup of the website's name in advance, and to open a connection to the site before attempting to retrieve content.
The code is placed in the try block to accommodate the possibility of a browser throwing an exception if the requested operations are not supported. The application does not consider lack of support an error and wants to continue anyway.
The end result is that if dns-prefetch or preconnect are supported the browser can take the hint and perform the operations. If they are not supported any error generated is ignored and code continues at the next statement - connecting to the website later will have to proceed at normal speed.

How to handle alert pop up with JavaScript? Selenium Webdriver

Selenium WebDriver 2.53.1.1
Visual Studio 2015
C#
The application I am testing has Alert Pop Ups which I handle with the following bit of code without problem
ts.getDriver().SwitchTo().Alert().Accept();
However I have ran into a new issue. Some of my webelements have issues of not being found anymore and therefore I have to run JavaScript to execute the web element (please see code below for handling the web element)
public void SelectHREFCID()
{
IJavaScriptExecutor js = ts.getDriver() as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click()",hrefCID);
try
{
ts.getDriver().SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException)
{
// do nothing...
}// Have to use this to find the hyperlink!
}
The only problem is immediately after js.ExecuteScript line runs, the Pop Up Displays and my Alert().Accept() line of code never fires off after this so the program just stops there with the pop up. I ran this line by line in debug and can't can't step to the next line once I execute the js.ExecuteScript line. Any advice on how to handle this?
UPdate At this point in my code (js.ExecuteScript))
, as soon as this line of code is executed i see this
Once this pop up displays My Selenium Code does not continue into the try catch statement to handle the Alert
Latest update as of 9/9
I tried the alert handle both ways
But my selenium code stops execution at the point of the pop up firing off
js.ExecuteScript("arguments[0].click().hrefCID);
**UPDATE 09/12****
I updated my window.alert and this resolved the issue (to confirm)
IJavaScriptExecutor js = ts.getDriver() as IJavaScriptExecutor;
js.ExecuteScript("window.confirm = function(){return true;}");
js.ExecuteScript("arguments[0].click()",hrefCID);
// js.ExecuteScript("window.alert = function() { return true;}");
I think this alert blocks the code execution, you should execute this script before click to override the confirmBox function using js as :-
js.ExecuteScript("window.confirm = function() { return true;}")
After that execute as below to perform click on button :-
js.ExecuteScript("arguments[0].click()",hrefCID);

Why won't javascript run one function if there is an error in the other function?

Why won't a JavaScript function run if there is an error in another function?
I ran this html page and tried to load the alert from the popup1() function, but it wouldn't work because there is an error in the if statement of the popup2() function:
<html>
<body>
<button onclick="popup1()"> Pop up 1 </button>
<button onclick="popup2()"> Pop up 2 </button>
<script>
function popup1()
{
alert ("Pop up 1");
}
function popup2()
{
if ( 1 = 1)
{
alert ("Pop up 2");
}
}
</script>
</body>
</html>
When I corrected the if statement to if (1 == 1), both functions worked.
Why did this affect the other function?
Is there any free software you can recommend that will find syntax errors in JavaScript for me, I really don't want to trawl through code again because of a missing equal sign. I tried eclipse for php but it didn't manage to find this.
Javascript runs in blocking sequence, so if there is any error anywhere it will stop execution.
(this is assuming you have no asynchronous function callbacks that started before the error happened)
The line of code if ( 1 = 1) is a parse error in Javascript. When your code fails to parse properly, the Javascript parser stops parsing your code immediately and that script is considered to have a fatal error and is not loaded.
At that point, it has found illegal Javascript and at best the parser has decided this is a fatal error and at worst, the parser is hopelessly confused about what your code would have meant and cannot proceed. In any case, this is how the Javascript parser works. It stops on the first parse error it encounters within any given script.
Your specific error would have been shown to you in the Javascript console as soon as you loaded that page. Your FIRST line of defense should be to keep your eye on the debug console. You should watch it regular, but ALWAYS look there whenever anything is not working as you expect.
In Chrome, it would have told you:
Uncaught ReferenceError: Invalid left-hand side in assignment
In addition, you can run various "lint" type programs on your code and it will advise you not only about errors, but also about dangerous practices. Personally, I use http://jshint.com/, but there are several different programs that offer this capability.
this error is because a number can not be redeclare, since a number always going to be the same number.
This causes a syntax error and affects the rest of the code. if you try to make this example work without problems.
function popup2()
{
var number = 1;
if ( number = 1)
{
alert ("Pop up 2");
}
}

IE9 not running javascript onload

For some reason, IE9 is not running my JavaScript code onload when the browser is launched for the first time that session. It seems to only run onload after the user refreshes the page. It will also run the JavaScript when the debug console is open.
How do I make it so the JavaScript runs onload after the browser is open? Is this just a bug of IE9?
I'll restate this so you understand: The code DOESN'T run if you go to the site after launching a new browser session. The code DOES run if you open the site in a new tab, or reload the page, or open the debug console
Here is the function I use to run my script onload (which works fine in NORMAL browsers):
(function (i) {
var u = navigator.userAgent;
var e = /*#cc_on!#*/
false;
var st = setTimeout;
if (/webkit/i.test(u)) {
st(function () {
var dr = document.readyState;
if (dr == "loaded" || dr == "complete") {
i()
} else {
st(arguments.callee, 10);
}
}, 10);
} else if ((/mozilla/i.test(u) && !/(compati)/.test(u)) || (/opera/i.test(u))) {
document.addEventListener("DOMContentLoaded", i, false);
} else if (e) {
(function () {
var t = document.createElement('doc:rdy');
try {
t.doScroll('left');
i();
t = null;
} catch (e) {
st(arguments.callee, 0);
}
})();
} else {
window.onload = i;
}
})(init); //init is the function to call onload
I had the exact same issue that you had. I had a set of images that I wanted to ensure were preloaded before I began starting a slideshow. I was making use of
$(window).load(function(){
//All my code
});
And this is exactly what I was facing.
When I copied and pasted the URL in IE, the onload event did not seem to fire.
If I open the console using F12 and then past the URL in the browser and pressed enter, the everything seemed to be working.
Now that I opened the console at least once,
If I closeed the console and then reloaded the page, the onload was firing.
If I typed the URL and then pressed enter, the onload was firing.
It took me a couple of days to actually figure out what I was doing wrong.
The issue was with the console.log statements. At a lot of places in my code, I had done a lot of console logging. Even one of the plugins that I was using - jplayer has a an uncommented console message somewhere in the code.
The issue was that, unless you open the console at least once in IE, the console object is not available. Which means that the code will fail at the first console.log that it encounters.
Now, I was in no mood to comment out all my console.log statements just for the sake of testing it in IE. So, this is what I did instead. Right at the top of my document.ready jquery function, I wrote this small snippet of code.
if(!window.console){
console={};
console.log = function(){};
}
What it basically does is creates a dummy console.log function placeholder so that the code can run in IE but it will work only as long as console.log is the only console function that you are making use of in your code or in your plugins.
Just my 2 cents. Been pulling my hair over this issue for longer than I care to admit. I hope this is useful to at least someone.
You need to figure out if the code doesn't run at all, I.e. never enters your function, or if it fails on some specific line inside your function. Does IE9 show any warnings or js errors?
The easiest thing to do is stick a bunch of alert() statements in the code to see where it stops and narrow down to that line.
If it never enters your function then you need to look higher, where the call is being made.
Just a small note; When you use any debugging keywords (like console.log) or anything related, IE9 will escape this JS function if and only if the debugger is not on (with F12)
Actually I don't know what else cause a problem, but for me, my problem was the word "console.log" while debugger not on in IE9 ... I know this is already an answered question, but I felt it needs to be be known.
Okay, I figured it out. It has to do with some weird way IE handles IF statements.
In my init function I had two IF statements, one which checked if a variable existed and then logged the value of that variable. The other which checked to see if the value of the same variable was equal to an arbitrary string.
After removing the first IF statement, everything seems to work properly. I also decided to use a different onload function which can be seen below:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, true);
} else if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag=document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete") {
init();
//ie('open');
}
}
}

Is it possible to stop JavaScript execution? [duplicate]

This question already has answers here:
How to terminate the script in JavaScript?
(25 answers)
Closed 7 years ago.
Is it possible in some way to stop or terminate JavaScript in a way that it prevents any further JavaScript-based execution from occuring, without reloading the browser?
I am thinking of a JavaScript equivalent of exit() in PHP.
Short answer:
throw new Error("Something went badly wrong!");
If you want to know more, keep reading.
Do you want to stop JavaScript's execution for developing/debugging?
The expression debugger; in your code, will halt the page execution, and then your browser's developer tools will allow you to review the state of your page at the moment it was frozen.
Do you want to stop your application arbitrarily and by design?
On error?
Instead of trying to stop everything, let your code handle the error. Read about Exceptions by googling. They are a smart way to let your code "jump" to error handling procedures without using tedious if/else blocks.
After reading about them, if you believe that interrupting the whole code is absolutely the only option, throwing an exception that is not going to be "caught" anywhere except in your application's "root" scope is the solution:
// creates a new exception type:
function FatalError(){ Error.apply(this, arguments); this.name = "FatalError"; }
FatalError.prototype = Object.create(Error.prototype);
// and then, use this to trigger the error:
throw new FatalError("Something went badly wrong!");
be sure you don't have catch() blocks that catch any exception; in this case modify them to rethrow your "FatalError" exception:
catch(exc){ if(exc instanceof FatalError) throw exc; else /* current code here */ }
When a task completes or an arbitrary event happens?
return; will terminate the current function's execution flow.
if(someEventHappened) return; // Will prevent subsequent code from being executed
alert("This alert will never be shown.");
Note: return; works only within a function.
In both cases...
...you may want to know how to stop asynchronous code as well. It's done with clearTimeout and clearInterval. Finally, to stop XHR (Ajax) requests, you can use the xhrObj.abort() method (which is available in jQuery as well).
You can make a JavaScript typo :D (thinking outside the box here)
thisFunctionDoesNotExistAndWasCreatedWithTheOnlyPurposeOfStopJavascriptExecutionOfAllTypesIncludingCatchAndAnyArbitraryWeirdScenario();
Or something like:
new new
Something like this might work:
function javascript_abort()
{
throw new Error('This is not an error. This is just to abort javascript');
}
Taken from here:
http://vikku.info/codesnippets/javascript/forcing-javascript-to-abort-stop-javascript-execution-at-any-time/
I do:
setTimeout(function() { debugger; }, 5000)
this way I have 5 seconds to interact with UI and then in stops. Las time I used was when I needed to leave custom tooltip visible, to do some styling changes.
No.
Even if you throw an exception, it will only kill the current event loop. Callbacks passed to setTimeout or DOM/XMLHttpRequest event handlers will still run when their time comes.
I am using
return false;
if I want to abort from JavaScript from running further downwards.
If you're in a function you can exit it using return; but that doesn't stop execution of the parent function that called that function.
You can call return early in a function, and at least that function will stop running. You can also just use throw '' to cause an error and stop the current process. But these won't stop everything. setTimeout and setInterval can make delayed functions and functions that run on a time interval, respectively. Those will continue to run. Javascript events will also continue to work as usual.
I know this is old, but I wanted to do this and I have found, in my opinion, a slightly improved solution of the throw answers. Just temporary supress the error messages and reactivate them later using setTimeout :
setTimeout(function() {
window.onerror = function(message, url, lineNumber) {
return false;
};
}, 50); // sets a slight delay and then restores normal error reporting
window.onerror = function(message, url, lineNumber) {
return true;
};
throw new Error('controlledError');
Define a variable inside the JavaScript function, set this variable to 1 if you want ot execute the function and set it to 0 if you want to stop it
var execute;
function do_something()
{
if (execute == 1)
{
// execute your function
}
else
{
// do nothing
}
}
The process is tedious, but in Firefox:
Open a blank tab/window to create a new environment for the script
from the current page
Populate that new environment with the script to execute
Activate the script in the new environment
Close (that is, kill) that new environment to ...
stop or terminate JavaScript this [in a] way to [that it] prevent[s] any further
JavaScript-based execution from occuring, without reloading the browser
Notes:
Step 4 only stops execution of JavaScript in that environment and not the scripts of any other windows
The original page is not reloaded but a new tab/window is loaded with the script
When a tab/window is closed, everything in that environment is gone: all remnants, partial results, code, etc.
Results must migrate back to the parent or another window for preservation
To rerun the code, the above steps must be repeated
Other browsers have and use different conventions.

Categories