Automatically answer a window.confirm using VBA - javascript

I have some VBA code that opens a webpage, then calls a javascript function that deletes a file off of the page. When this function is called, it calls a window.confirm in the HTML to make sure that the user really wants to delete the file. The options are yes and cancel. My question- Is there any way to automatically make my VBA code answer yes? As it is, I can automate everything but the "yes" click, which means I still have to sit there and click yes for every file that it wants to delete; it'd be nice to run the code and be able to walk away.
edit: if it helps, here is the code I'm using to execute the javascipt. Also, the javascript function code
My code:
Dim CurrentWindow As HTMLWindowProxy: Set CurrentWindow = IE.Document.parentWindow
m = 2
Do Until date_var < "2011-7-1"
Cells(1, 11).Value = Range("j1") - m
date_var = Cells(1, 11).Value
date_var = Format(date_var, "yyyy-m-d")
Call CurrentWindow.execScript("Delete('filepath_here_" & date_var & ".csv?DELETE')")
Javascript Function:
<SCRIPT LANGUAGE="JavaScript">
function Delete(What)
{
if (window.confirm("Do you really want to delete this file"))
{
location.href = What;
}
}
</SCRIPT>

I don't know VBA, but try the following script:
Call CurrentWindow.execScript("location.href='filepath_here_" & date_var & ".csv?DELETE';")
That should do the trick. It's better than calling the delete function directly. No function call overhead, no side effects, and no confirm box. Replace the last line of your code with this one and check.

You could try executing this piece of code when the page loads:
window.confirm = function() {
return true;
};

Related

How do I get a function to run with the .onsubmit event?

There is probably a really easy solution to this but I cannot for the life of me work out how to fix this issue, and nothing I have found so far has done the trick.
I'm trying to get the function "validate" to run when the form "apply" is submitted:
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
applyForm.onsubmit = validate;
}
Validate looks like the following:
function validate() {
alert("If this alert is up then validate is running");
var dateOfBirth = document.getElementById("dob").value;
var state = document.getElementById("state").value;
var postcode = document.getElementById("postcode").value;
etc.
The function "setJobValue" is running (so I know init is working) and there are no errors in the console, but what adjustments would I have to make for validate to be called?
Well, what happens is that when you put your code above in the head, the script runs when the HTML gets rendered. So during that time, it allocates different memory and function blocks. So when you call that function again, then it gives you different results and no errors because of the existing references. Well its a bit weird but its the way JS works and it is always recommended to put your JS code at the bottom of the page.
You can directly call validate method from your init method instead.
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
validate();
}
When we assign a function to an event, it will fire at last.
so in your case, This should work
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
applyForm.onsubmit = functionToSave;
}
And call your validation method on the submit button onclick event.

How to call JavaScript function in VBA?

I need to by pass an IE confirm 'OK'/'Cancel' pop-up message. I have a problem running a JavaScript function in my VBA script. My JavaScript:
function ConfirmSave()
{
var Ok = confirm('Are you sure all Documents and Information are attached and correct before saving?');
if(Ok)
return true;
else
return false;
}
function submitbutton_click() {
document.getElementById('FileAttachement2_hdnButtonFlag').value = "SAVE";
var submitbutton = document.getElementById('cmdDownSave');
var uploadobj=document.getElementById('FileAttachement2_Uploader1');
if(!window.filesuploaded)
{
if (!ConfirmSave()) return false;
if(uploadobj.getqueuecount()>0)
{
uploadobj.startupload();
}
else
{
//var uploadedcount=parseInt(submitbutton.getAttribute("itemcount"))||0;
//if(uploadedcount>0)
//{
return true;
//}
//alert("Please browse files for upload");
}
return false;
}
window.filesuploaded=false;
return true;
}
In manual process, when I click the save button, the page will pop-up a confirm message box, and my macro will stop running when the pop-up appears unless it has been clicked.
Here is the code I have tried, to click the save button,
Set ElementNameV = HTMLDoc.getElementsByName("cmdsave")
ElementNameV(0).click
I also tried using removeattribute and setattribute with which the pop-up message disappeared but it doesn't upload the file because I need to press the 'OK' in confirm message box that will appear upon clicking the save button to start the file uploading.
ElementNameV(0).removeAttribute ("onclick")
ElementNameV(0).setAttribute "onclick", "return true"
ElementNameV(0).click
I tried running the JavaScript function using below script but it also shows the confirm pop-up message box:
Call HTMLDoc.parentWindow.execScript("submitbutton_click()")
You should be able to overwrite the ConfirmSave function with one which simply returns true:
HTMLDoc.parentWindow.execScript "window.ConfirmSave = function(){return true;};"
or
HTMLDoc.parentWindow.execScript "window.confirm = function(){return true;};"
or even
HTMLDoc.parentWindow.eval "window.confirm = function(){return true;};"
Run that before clicking the button.
Tested and works in IE11
So I've read your question a few times now and I think that to achieve what you want to do you are going to have to completely change your approach to the problem. You need to read up on Javascript Concurency, Javascript Web Workers, and the Javascript Event Loop.
Just throw these terms into Google and you'll find lots of great resources to learn about this.
By default Javascript is a single threaded language and it halts while waiting for events to complete their activities. What you seem to be looking for based on how I'm reading your question is a way for your Javascript to keep performing actions while a user prompt is being displayed.
While this is not an endorsement, I will throw out this one link to get you started.

Does JQuery $.post() not work with document.onbeforeunload event?

I am trying to use $.post to send form data to a server side script to be saved if the user tries to leave the page without submitting the form. I am using the same function attached to a save button and on setInterval set to every 2 minutes, and it works fine. But when I attach the function to document.onbeforeunload it does not work. In firebug, I see the request is being sent, but it looks like it is being stopped before a status code is returned and the page continues to unload. I am still pretty new to Javascript and Jquery and I am not sure if maybe $.post is one of those functions that might not work on the onbeforeunload event. If that is true, is there another way I can send the data if the user tries to leave the page without saving?
This is the function I am calling from the onbeforeunload event:
function ajaxSubmit(){
var blogtitle = $("#title").val();
var publishedstate = 0;
var blogid = $("#blogID").val();
var blogbody = CKEDITOR.instances['body'].getData();
var postdata = {ajaxSubmit:true,title:blogtitle,body:blogbody,published:publishedstate,blog_id:blogid};
$.post('ajaxblog.php',postdata,function(data){
$("#autosaveMessage").html(data);
$("#autosaveMessage").show();
setTimeout(function(){$("#autosaveMessage").hide();},5000);
});
}
and this is how I am calling the function:
var post_clicked = false;
$("#postButton").click(function(){
post_clicked = true;
});
function leaveEditor(){
if(post_clicked==false){
ajaxSubmit();
}
else{
//Do Nothing
}
}
window.onbeforeunload = leaveEditor;
No, and this is by design. It would be remarkably troublesome if a page could use onbeforeunload to indefinitely delay browsing away, persist its presence somehow, etc. One of the most important abilities for a user of a web browser to have is the ability to leave.
Just use the stringy return value—the whole point of it is to remind the user that s/he made changes that will be lost. Like on SO :)

ajaxtoolkit progress update javascript

I am using ajaxtoolkit modalpopupextender to display a processing message. It's working fine on a typical postback (button click, etc).
However, I am calling a postback in javascript and the progress message isn't showing UNLESS I add an "alert" in the javascript.
Here's my javascript:
function getOrder() {
beginRequest('', '')
var hid = document.getElementById("ctl00_ContentPlaceHolder_hid");
//alert(hid.value);
__doPostBack("SaveOrder", hid.value);
endRequest('', '')
}
I obviously don't want to have an "alert" so does anyone have a solution or ran into this?
Here's the other pience of javascript used relating to this (typical stuff):
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
var mdlCtl = document.getElementById('ctl00_hfModalCtlID').value;
function beginRequest(sender, args){
$find(mdlCtl).show();
}
function endRequest(sender, args) {
$find(mdlCtl).hide();
}
I'm stumped on why the "alert" makes a difference in the javascript that shows the processing message...?
Thoughts? Ideas?

Event when navigateToURL has finished in flex

I am using navigateToURL for file downloading from server. Is there anyway possible to know when navigateToURL has finished, more like when browser download dialog has opened?
Sometimes it takes 5 seconds to complete, user might get confused and start clicking download button like psychopath, which can result in multiple download dialogs opened.
I want to add some "please wait" text or something before it finishes (I already have one, I just need to know when to stop).
Maybe it can be done using javascript and get info from ExternalInterface?
This is kind of crazy, but I can't think of any other way: you could put the request object into a dictionary which is set to weak reference the keys, and then check on intervals whether the key was removed.
However, I'm not sure what will happen first, either the SWF itself will be disposed or the dictionary will be cleaned. It's also possible that given the one-time-ness of the function the reference to the request object isn't deleted because it is assumed to be deleted together with the whole SWF.
One more thing that I know is that uncaught error events will catch events from navigateToURL - not really helpful, but at least may give you the indication if it didn't work.
One more simple thing I can think of - just disable the button for a short time, like 1-2 seconds. If it worked, no one will see the delay, and if it didn't, they won't be able to press it too often.
private var _requestStore:Dictionary = new Dictionary(true);
private var _timer:Timer = new Timer(10);
. . .
_timer.addEventListener(TimerEvent.TIMER, timerHandler);
. . .
public function openURL(url:String):void
{
var request:URLRequest = new URLRequest(url);
_requestStore[request] = true;
_timer.start();
navigateToURL(request);
}
private function timerHandler(event:TimerEvent):void
{
var found:Boolean;
for (var o:Object in _requestStore)
{
found = true;
break;
}
if (!found) // the request got disposed
}
Is there anyway possible to know when navigateToURL has finished, more
like when browser download dialog has opened?
No, there is not. Once you pass a request onto the browser; the Flash Player no longer has any control or access to it.
You mention using ExternalInterface as part of a possible solution, but how would your HTML/JavaScript page know that a download had been finished?
navigateToURL does not fire a complete event. Try using this event from Adobe's help documentation:
public function URLRequestExample() {
loader = new URLLoader();
configureListeners(loader);
var request:URLRequest = new URLRequest("XMLFile.xml");
try {
loader.load(request);
} catch (error:Error) {
trace("Unable to load requested document.");
}
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html#includeExamplesSummary

Categories