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.
Related
Hi i am using selenium webdriver to automate my script and i have used wait.until condition in my script to click on the delivery bttn in below html page. The problem is selenium is finding my element but since the java script reloads the certain element. And the delivery bttn only becomes clickable after reloading. And my selenium script throws "stale element reference: element is not attached to the page document". What should i do to overcome this error.
WebElement delibttn=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//button[#class='btn-to-cart nopricetohide btn btn-primary your-catalog-deliver btn-block btn-unpadded tocart-rounded'])[1]")));
delibttn.click();
WebElement contshopping=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='btn btn-link full-width mb-10']")));
Screenshot:
there are two ways to solve your problem.
1) Run the code with Async, that way you can 'await' a line of code, for example..
function async(test1){
await driver.findElement(By.id("");
driver.click();
});
or you can also do the following
2)
function (test1) {
let element = driver.findElement(By.id(elementId));
driver.wait(until.elementIsVisible(element), 10000).then(async () =>{
element.click();
});
This wait in number 2, is the one that i use in my code and it always works.
A very barbaric way of doing it would be to add a ridiculous wait time to check that it isn't something else showing an error similar to a wait problem
driver.sleep(10000);
or
thread.sleep(10000);
(the measurement is in milliseconds unless defined otherwise)
Please let me know if these solutions do not solve the problem.
as Jack suggested you could use async, but I always used an infinte while loop
Code i have given below is in python, but you can use the logic in java too
def wait_for_element():
val = True
while val:
web_elem = driver.find_element_by_id('id')
try:
web_elem.is_displayed()
except Exception as ex:
val = True
else:
val = False
i know infinite loop is not a better way than async, but if there are cases where you can't use async you can use this. Also keep in mind to put timeout for loop, otherwise you would looping infinitely when the page was unresponsive or has not loaded.
the reason it is still throwing this issue is because you are not handling your exceptions properly, this is a response to it still throwing stale element errors.
Add something like this to your project, if you look at the bottom of my code you will see that i have added exceptions to catch errors so it does not affect the code the way it is doing.
driver.findElement(By.id(buttonID)).then(pageElement => {
driver.wait(until.elementIsVisible(pageElement), 10000).then( () => {
pageElement.click();
next();
})
.catch(ex => {
console.log(ex.message, ex.stack)
});
}).catch(ex => {console.log(ex.message, ex.stack)});
This is the example of how i am using catches, however many promises you have in your function the more catches you will need, if you hover over an element in Visual Code / Studio you will be able to see if it throws a promise or not.
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
What is the difference between these two statements, and is there a good reason to use one over the other?
throw Error("msg");
console.error("msg");
In my limited experience, I've only really seen throw Error() used. Is there any particular reason why?
Also, is there an equivalent to console.warn() in the same fashion?
throw ... raises an exception in the current code block and causes it to exit, or to flow to next catch statement if raised in a try block.
console.error just prints out a red message to the browser developer tools javascript console and does not cause any changes of the execution flow.
Some of the Differences are:
throw Error("msg"):
Stops js execution.
Mostly used for code handling purpose.
Can alter main flow of execution.
This syntax is mostly same for all browser as this is specified and validated by W3C.
console.error("msg"):
It just shows output in Red color at Browser console
It is mostly used to print values for debugging purpose.
Cannot harm main flow of execution.
This Syntax sometimes vary according to vendor browser and not standardized by W3C.
i.e. For IE accepted syntax is window.console.debug("msg")
Throw is for actually changing the control flow (jumping out of the current context and up to an error handler) for handling errors programmatically. The console statement is just for debugging and printing text to the error console. You may see them used in conjunction, for example:
var doSomethingDangerous = function(response) {
if (isMalformed(response)) {
throw Error('Response is malformed.');
}
process(response);
};
var sendAsyncRequest = function() {
var request = buildAsyncRequest();
request.sendThen(function (response) {
try {
doSomethingDangerous(response);
} catch (e) {
console.error(e);
doSomeAdditionalErrorHandling();
}
});
};
efor this problem i am using Node-Webkit (node.js) and Async, loading a Windows App.
The reason of this question is to definitively answer:
What really means asynchronous execution in Javascript and Node.Js.
My personal code problem is at the end of the Question. "The Case".
I am going to explain all about the problem i have directly with a schematic summary. (And I will be updating the info as you help me to understand it)
The Concept (theory)
Imagine a Primary Screen (JS, Html, css, ... Node.js frameworks) and a Background Procedure (JS execution every 10 min, JS internal checks, background Database Optimization, ...).
Whatever you do in Primary Screen wont affect background execution (except some important cases), and Background can change even the Screen if he needs to (screen timers, info about online web status, ...)
Then the behaviour is like:
Thread 1: Your actions inside the App framework. Thread 2: Background App routines
Any action as they finish gives his output to screen, despite of the rest of the actions in async parallel
The Interpretation (For me)
I think this is something that "Async" will handle without problems, as a parallel execution.
async.parallel([
function(){ ... },
function(){ ... }
], callback); //optional callback
So the Thread 1 and Thread 2 can work together correctly while they do not affect the same code or instruction.
The Content will be changing while any threads request something of/to it.
The Implementation (Reality)
Code is not fully asynchronous during the execution, there are sync parts with common actions, that when they need calls the async codes.
Sync: Startup with containers -> Async: load multiple content and do general stuff -> Sync: Do an action in the screen -> ...
The Case
So here it is my not working properly code:
win.on('loaded', function() {
$( "#ContentProgram" ).load( "view/launcherWorkSpace.html", function() {
$("#bgLauncher").hide();
win.show();
async.parallel([
function() //**Background Process: Access to DB and return HTML content**
{
var datacontent = new data.GetActiveData();
var exeSQL = new data.conn(datacontent);
if(exeSQL.Res)
{
var r = exeSQL.Content;
if(r.Found)
{
logSalon = new data.activeSData(r)
$('#RelativeInfo').empty();
$("#RelativeInfo").html("<h4 class='text-success'>Data found: <b>" + logData.getName + "</b></h4>");
}
}
},
function() //**Foreground Process: See an effect on screen during load.**
{
$("#bgLauncher").fadeIn(400);
$("#centralAccess").delay(500).animate({bottom:0},200);
}
]);
});
});
As you can see, im not using "Callback()" because i dont need to (and it does the same).
I want to do the Foreground Process even if Background Process is not finished, but the result of the code is done at same time when both request has finished...
If i disconect the DB manually, first function takes 3 seconds until gives an exception (that i wont handle). Until then, both proccess will not output (show on screen) anything. (Foreground Process should be launched whatever happends to Background Process).
Thanks and sorry for so much explanation for something that looks like trivial.
EDITED
This start to be annoying... I tried without Async, just a javascript with callback like this:
launchEffect(function () {
var datacontent = new data.GetActiveData();
var exeSQL = new data.conn(datacontent);
if(exeSQL.Res)
{
var r = exeSQL.Content;
if(r.Found)
{
logData = new data.activeData(r)
$('#RelativeInfo').empty();
$("#RelativeInfo").html("<h4 class='text-success'>Salón: <b>" + log.getName + "</b></h4>");
}
}
});
});
});
function launchEffect(callback)
{
$("#bgLauncher").fadeIn(400);
$("#centralAccess").delay(500).animate({bottom:0},200);
callback();
}
Even with this... Jquery doesnt work until the callback answer...
node-webkit let's you run code written like code for node.js, but is ultimately just a shim running in WebKit's Javascript runtime and only has one thread, which means that most 'asynchronous' code will still block the execution of any other code.
If you were running node.js itself, you'd see different behavior because it can do genuinely asynchronous threading behind the scenes. If you want more threads, you'll need to supply them in your host app.
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.