OK I have a method from the code behind that creates a popupwindow. Then there's a line of code that executes after that Im wondering when does that line of code executes, If it executes after using the popupwindow or right after it creates the popupwindow?
EX:
void exPopupWindowMethod()
{
string scr = "window.open('examplePopup.aspx','popup_window',.....);";
ClientScript.RegisterStartupScript(this.GetType(), "script", scr, true);
}
String example = "example"; //initialization
exPopupWindowMethod();// the method that creates the popup window
example=null;
I dont know if theres a duplicate question for this but pls consider my question. I need to clarify this for using of sessions thanks!
The example=null line will be executed immediately (i.e. before the popup window is shown).
The reason for this is that the ClientScript.RegisterStartupScript wraps the code in a document.ready loop which will wait until the rest of the page has completed loading before executing.
Because the example=null line isn't waiting for the rest of the DOM to load, it will execute immediately.
ClientScript.RegisterStartupScript on MSDN
Just replace the code after the popup with something like : Response.Write("Test");
And check if the response is done while or after the popup shows?
Related
I have three (3) javascripts that I am trying to execute in a specific order. My problem is that each javascript uses data set by the previous script. My first script, which executes on loading, gets data from an SQL database and copies it to the body of my web page. The next javascript needs some of this data to execute properly In order to execute the second script, I must wait not only until the previous script has completed execution but until the data has been loaded to the body of my web page so that it can be accessed by the second script. The relationship between the second and third scripts is similar. I've not been able to find any previous question and answer that addresses the use of data extracted by a previous script. Any help that you can offer will be very much appreciated. Here's an example of my latest attempt.
function myFunction()
{
document.getElementById("inputCounter").innerHTML = 1;
var recordCounter = document.getElementById("inputCounter");
var number = recordCounter.innerHTML;
querySQL(number);
document.onreadystatechange = function()
{
if (document.readystate == "complete")
{
getIPDetail('https://freegeoip.net/csv/');
}
};
}
myFunction() executes on loading of the page body. The first script called from myFuntion() is querySQL(number). The second script called from myFunction() is getIPDetail('https://freegeoip/csv/'). My problem is that detIPDetail... does not execute because it needs data that querySQL inserts into a div on the page body.
I was able to solve this problem through experimentation. In other words, I found the right positions in my code to put the javascript function calls so that my application flowed properly.
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);
I need to add a Javascript event for CollapsiblePanelExtender on Javascript pageload of the page. Following is the definition of CollapsiblePanelExtender:
<cc1:CollapsiblePanelExtender ID="cpe" runat="Server" TargetControlID="pnlInstances"
BehaviorID="cpe" ImageControlID="lnkWebroleAction" ExpandedImage="~/App_Themes/Default/images/MonitorDownArrow16.png"CollapsedImage="~/App_Themes/Default/images/MonitorLeftArrow16.png"
CollapsedSize="0" Collapsed="false" ExpandControlID="lnkWebroleAction" CollapseControlID="lnkWebroleAction"
AutoCollapse="false" AutoExpand="false" ExpandDirection="Vertical" SuppressPostBack="true" />
And following is the Javascript code I am executing:
window.onload = pageLoad1();
function pageLoad1() {$find("cpe").add_expandComplete(coll_ExpandedComplete);
}
The problem is $find("cpe") returns null on this event. If I execute the same function from button click I can find the object.
Which other load events of Javascript I can use? I have tried $(documnt).ready.
You're not assigning the pageLoad1 function to window.onload, you're calling it immediately and assigning the value it returns (i.e. undefined).
You have to write:
window.onload = pageLoad1; // No parenthesis.
function pageLoad1() {
$find("cpe").add_expandComplete(coll_ExpandedComplete);
}
Or, alternatively, write a pageLoad() function, which will be called automatically by the framework when the page finishes loading:
function pageLoad() {
$find("cpe").add_expandComplete(coll_ExpandedComplete);
}
I agree with OP; there is (as original answerer pointed out) an error in the original post which is sufficient to make it look like there is not a real problem here; but I have a complex JS/Ajax driven page, and some code which tries to get some ASP.NET Ajax CollapsiblePanelExtender objects by their BehaviorID in a JS function which /is/ called on PageLoad.
These objects are usually ready, but sometimes aren't; if if try to run the code with a slight delay (100ms) they are ready. But delaying for a fixed time is not great; what event can I use, to know that these ASP.NET Ajax objects have finished building themselves?
I understand that JS is single threaded and synchronously executed. Therefore when i add a file to my browser head tag that file is executed as soon as its encountered. Then it goes to the next script tag & executes that file. My question is when I add a js file dynamically to an HTML head tag. How does the browser executes that file?
Is it like that the file is executed as soon as the file is loaded wherever the current execution is. Or is it that we can control how that file is executed?
When the script is loaded, it will be executed as soon as possible. That is, if some other javascript function is executing, like a clickhandler or whatever, that will be allowed to finish first - but this is a given because, as you say, in browsers JavaScript normally execute in a single thread.
You can't control that part of the script loading, but you could use this pattern - heavily inspired by JSONP:
inserted script:
(function () {
var module = {
init: function () {
/* ... */
}
}
ready(module); // hook into "parent script"
}());
script on main page:
function ready(o) {
// call init in loaded whenever you are ready for it...
setTimeout(function () { o.init(); }, 1000);
}
The key here is the ready function that is defined on your page, and called from the script you insert dynmaically. Instead of immediately starting to act, the script will only tell the parent page that it is loaded, and the parent page can then call back to the inserted scripts init function whenever it wants execution to start.
What happens when a JavaScript file is dynamically loaded ( very simplified, no checks ):
the file is loaded;
if there is function call e.g. doSomething() or (function(){...})(), the code is executed(of course you must have the definitions);
if there are only function definitions, nothing is happening until the function call.
See this example: 3 files are loaded, 2 are executed immediately, 1 is waiting the timeout.
Edit:
The script tag can be placed anywhere in the page. Actually it is better to be placed at the end of the page if the onload event is not used (yahoo speed tips).
With HTML5 JavaScript has web workers MDN MSDN wikipedia.
Considering a way to do this is
var js=document.createElement('script')
js.setAttribute("type","text/javascript")
js.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(js);
// ^ However this technique has been pointed to be not so trusworthy (Read the link in the comment by Pomeh)
But answering your question
How does the browser executes that file?
As soon as the script is added to the DOM
Is it like that the file is executed as soon as the file is loaded wherever the current execution is?
Yes
Or is it that we can control how that file is executed?
Its better if you attach an onload event handler, rather than a nasty tricks.
Here is some code you can try to get an answer to your question.
<script>
var s = document.createElement('script'), f = 1;
s.src="http://code.jquery.com/jquery-1.7.2.js";
document.head.appendChild(s)
s.onload = function(){
console.log(2);
f = 0
}
while(f){
console.log(1);
}
</script>
This code should ideally print a 2 when the script loads, but if you notice, that never happens
Note: This WILL kill you browser!
My javascript code is added to random websites. I would like to be able to report to my server when a (specific) link/button on the a website is clicked. However I want to do it without any possible interruption to the website execution under any circumstances (such as error in my code, or my server id down etc.). In other words I want the site to do its default action regardless of my code.
The simple way to do it is adding event listener to the click event, calling the server synchronously to make sure the call is registered and then to execute the click. But I don't want my site and code to be able to cause the click not to complete.
Any other ideas on how to do that?
As long as you don't return false; inside your callback and your AJAX is asynchronous I don't think you'll have any problems with your links not working.
$("a.track").mousedown(function(){ $.post("/tools/track.php") })
I would also suggest you encapsulating this whole logyc inside a try{} catch() block so that any errors encauntered will not prevent the normal click behaviour to continue.
Perhaps something like this? I haven't tested it so it may contain some typo's but the idea is the same...
<script type="text/javascript">
function mylinkwasclicked(id){
try{
//this function is called asynchronously
setTimeOut('handlingfunctionname('+id+');',10);
}catch(e){
//on whatever error occured nothing was interrupted
}
//always return true to allow the execution of the link
return true;
}
</script>
then your link could look like this:
<a id="linkidentifier" href="somelink.html" onclick="mylinkwasclicked(5)" >click me!</a>
or you could add the onclick dynamically:
<script type="text/javascript">
var link = document.getElementById('linkidentifier');
link.onclick=function(){mylinkwasclicked(5);};
</script>
Attach this function:
(new Image()).src = 'http://example.com/track?url=' + escape(this.href)
+ '&' + Math.random();
It is asynchronous (the 'pseudo image' is loaded in the background)
It can be cross domain (unlike ajax)
It uses the most basic Javascript functionalities
It can, however, miss some clicks, due to site unloading before the image request is done.
The click should be processed normally.
1) If your javascript code has an error, the page might show an error icon in the status bar but it will continue the processing, it won't hang.
2) If your ajax request is asynchronous, the page will make that request and process the click simultaneously. If your server was down and the ajax request happening in the background timed out, it won't cause the click event to not get processed.
If you do the request to your server synchronously, you'll block the execution of the original event handler until the response is received, if you do it asynchronously, the original behaviour of the link or button may be doing a form post or changing the url of the document, which will interrupt your asynchronous request.
Delay the page exit just long enough to ping your server url
function link_clicked(el)
{
try {
var img = new Image();
img.src = 'http://you?url=' + escape(el.href) + '&rand=' + math.random();
window.onbeforeunload = wait;
}catch(e){}
return true;
}
function wait()
{
for (var a=0; a<100000000; a++){}
// do not return anything or a message window will appear
}
so what we've done is add a small delay to the page exit to give the outbound ping enough time to register. You could also just call wait() in the click handler but that would add an unnecessary delay to links that don't exit the page. Set the delay to whatever gives good results without slowing down the user noticeably. Anything more than a second would be rude but a second is a long time for a request roundtrip that returns no data. Just make sure your server doesn't need any longer to process the request or simply dump to a log and process that later.