Async JavaScript Function on Client Side( how to write call back) - javascript

i m facing a problem basically i have long running task that reads encoded bytes and then parse the bytes to find data in it.
functionLongRunningTask() {
//bytes returned from office.js (GetFileAsync Method)
var documentText = OSF.OUtil.encodeBase64(resultSlice.value.data);
// Open the document, which is stored as a base64 string.
var doc = new openXml.OpenXmlPackage(documentText);
var customXMLpart = doc.getPartByUri("/customXml/item1.xml");
if (customXMLpart == 'undefined' || customXMLpart == null) {
window.location = 'Page1.aspx'
}
else {
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(customXMLpart.data, "text/xml");
}
var customxml = xmlDoc.getElementsByTagName("DocumentID");
var documentid = 0;
for (var i = 0; i < customxml.length; i++) {
documentid = customxml[i].textContent;
}
window.location = 'Page2.aspx?documentid=' + documentid;
}
}
all of reading and traversing done on client side no server side involved in it. now as my application running in office word 2013 (Office APP basically) when i run this long Running task in synchronous way . UI gets freezed and stop responding and it restart Office APP.
i need to do it in Asynchronous way so UI dont get freeze i am using HTML5 and IE 9+. Any help will be appreciated
Regards

You wont have access to the DOM Parser in a WebWorker, so this method is not applicable. You will need to run portions of the code on a timer event.
Here is a library that may be able to help with running code against a timer -> https://github.com/jameswestgate/taskjs

Related

How to make browser save a remote file and get informed by a callback with Javascript/jQuery

I have encountered a problem with my Java script/jQuery code.
I want to make a piece of code which could fulfill the following requirement:
1.Make the browser save my remote binary file, let's say http://192.168.0.100/system/diagdata
2.Since the preparing the file in the server side with cost some time(usually around 40s), so I need a callback to let me know when the data will be ready to download(the file itself is very small, so let's ignore the actually data transmit duration) so that I could display some kind of loading page to tell the user the downloading procedure is on the way.
At first, I make a piece of code like this without callback:
var elemIF = document.createElement("iframe");
elemIF.src = 'http://192.168.0.100/system/diagdata';
elemIF.style.display = "none";
document.body.appendChild(elemIF);
It works well(but without callback)
Then in order to make callback possible, then I added some code like this:
var deferred = jQuery.Deferred();
var elemIF = document.createElement("iframe");
elemIF.src = 'http://192.168.0.100/system/diagdata';
elemIF.style.display = "none";
document.body.appendChild(elemIF);
elemIF.defer = 'defer';
if (window.ActiveXObject) { // IE
sc.onreadystatechange = function() {
if ((that.readyState == 'loaded'
||that.readyState == 'complete') ) {
}
}
}
else { // Chrome, Safari, Firefox
elemIF.onload = function() {
alert("onload");
};
elemIF.onerror = function(e) {
alert("onerror");
};
}
deferred.promise();
After I run this piece of code, the "onload" has been called, but the browser did not tend to save the file "diagdata" but try to load it and report a parsing error exception.
Did anyone have a substitute solution which could not only make browser save the binary file but also will callback to inform the data ready status?

JavaScript to save MAFF in Firefox

I am experimenting with iMacros to automate as task that Firefox will do. I simply want to save the current page with the MAFF extension. The JavaScript that the iMacros forum has lead me to, is this:
// I stuck these variable in just to try something.
var doc = "http://www.traderjoes.com";
var file = "C:\\Export\\Test.maff";
var format = "MAFF";
// I stuck these variable in just to try something.
var MafObjects = {};
Components.utils.import("resource://maf/modules/mafObjects.jsm",
MafObjects);
var jobListener = {
onJobComplete: function(aJob, aResult) {
if (!Components.isSuccessCode(aResult)) {
// An error occurred
} else {
// The save operation completed successfully
}
},
onJobProgressChange: function(aJob, aWebProgress, aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress) { },
onStatusChange: function(aWebProgress, aRequest, aStatus,
aMessage) { }
};
var saveJob = new MafObjects.SaveJob(jobListener);
saveJob.addJobFromDocument(doc, file, format);
saveJob.start();
I was only getting an error on line 26 because this was sample code. With the little JavaScript I know I tried to add some variables on the lines before the code starts. The thing is that when I try to search for syntax example for the method .addJobFromDocument I don’t find much, just like two results. Is this a method of JavaScript? Usually with things from the DOM you will get a great deal of information on them.
Does anybody know a way of automating the save of MAFF of the current open tab in Firefox and then closing the browser? iMacros was something I came to and glad to see it features but really I just want to automate from a command line the saving of a URL as a MAFF archive The doc (that I got from iMacros forum) also had these code snippets but I don’t have much idea how to use them. Thanks
var fileUri = Components.
classes["#mozilla.org/network/io-service;1"].
getService(Components.interfaces.nsIIOService).
newFileURI(file);
var persistObject = new MafObjects.MafArchivePersist(null, format);
persistObject.saveDocument(doc, fileUri);
Also:
var doc = gBrowser.contentDocument;
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\My Documents\\Test.maff");
var format = "TypeMAFF";

How do I use jQuery in Windows Script Host?

I'm working on some code that needs to parse numerous files that contain fragments of HTML. It seems that jQuery would be very useful for this, but when I try to load jQuery into something like WScript or CScript, it throws an error because of jQuery's many references to the window object.
What practical way is there to use jQuery in code that runs without a browser?
Update: In response to the comments, I have successfully written JavaScript code to read the contents of files using new ActiveXObject('Scripting.FileSystemObject');. I know that ActiveX is evil, but this is just an internal project to get some data out of some files that contain HTML fragments and into a proper database.
Another Update: My code so far looks about like this:
var fileIo, here;
fileIo = new ActiveXObject('Scripting.FileSystemObject');
here = unescape(fileIo.GetParentFolderName(WScript.ScriptFullName) + "\\");
(function() {
var files, thisFile, thisFileName, thisFileText;
for (files = new Enumerator(fileIo.GetFolder(here).files); !files.atEnd(); files.moveNext()) {
thisFileName = files.item().Name;
thisFile = fileIo.OpenTextFile(here + thisFileName);
thisFileText = thisFile.ReadAll();
// I want to do something like this:
s = $(thisFileText).find('input#txtFoo').val();
}
})();
Update: I posted this question on the jQuery forums as well: http://forum.jquery.com/topic/how-to-use-jquery-without-a-browser#14737000003719577
Following along with your code, you could create an instance of IE using Windows Script Host, load your html file in to the instance, append jQuery dynamically to the loaded page, then script from that.
This works in IE8 with XP, but I'm aware of some security issues in Windows 7/IE9. IF you run into problems you could try lowering your security settings.
var fileIo, here, ie;
fileIo = new ActiveXObject('Scripting.FileSystemObject');
here = unescape(fileIo.GetParentFolderName(WScript.ScriptFullName) + "\\");
ie = new ActiveXObject("InternetExplorer.Application");
ie.visible = true
function loadDoc(src) {
var head, script;
ie.Navigate(src);
while(ie.busy){
WScript.sleep(100);
}
head = ie.document.getElementsByTagName("head")[0];
script = ie.document.createElement('script');
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
head.appendChild(script);
return ie.document.parentWindow;
}
(function() {
var files, thisFile, win;
for (files = new Enumerator(fileIo.GetFolder(here).files); !files.atEnd(); files.moveNext()) {
thisFile = files.item();
if(fileIo.GetExtensionName(thisFile)=="htm") {
win = loadDoc(thisFile);
// your jQuery reference = win.$
WScript.echo(thisFile + ": " + win.$('input#txtFoo').val());
}
}
})();
This is pretty easy to do in Node.js with the cheerio package. You can read in arbitrary HTML from whatever source you want, parse it with cheerio and then access the parsed elements using jQuery style selectors.

How to get timezone before postback

I am making a page that accepts post data from any number of pages that I cannot change, access, or in any way control.
I need, in one way or another, to get the timezone of the user. I know, ideally the posting page would do this, but I cannot access these pages.
I've read other answers on this site and come up with 2 almost, but not quite there solutions.
First, there is javascript. I can get the javascript function to return (or change a label to) the correct value, but the problem is I need this info before the postback. I've been trying to write the timezone name on another page and read that page, but I have no idea how to begin to do that? Any other workaround to use the javascript is welcome, or any way to force call this before Page_Load is called?
function getTimeZone()
{
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
var label = document.getElementById("<%=TZ.ClientID%>");
label.textContent = "GMT " + gmtHours;
}
The second solution is to read it from another page, and I am using this:
http://ipinfodb.com/ip_query.php?ip=192.36.167.120&timezone=true
(Completely random ip in there, btw)
So here is my function to get the info from that site:
public string GetTimezone(string ip)
{
string address = string.Format("http://ipinfodb.com/ip_query.php?ip={0}&timezone=true", ip);
string timezone = "";
try
{
XmlTextReader reader = new XmlTextReader(address);
HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(address);
wrq.Proxy.Credentials = CredentialCache.DefaultCredentials;
reader = new XmlTextReader(wrq.GetResponse().GetResponseStream());
string lastRead = "";
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
lastRead = reader.Name;
}
if (reader.NodeType == XmlNodeType.Text)
{
if (string.Compare(lastRead, "TimezoneName", true) == 0)
{
timezone = reader.Value;
break;
}
}
}
}
catch
{
timezone = "";
}
return timezone;
}
Basically, this works in debug mode, but when it's live only an empty string is returned. I am baffled? Is there any better way to read data from a page? I am using Request.ServerVariables["REMOTE_ADDR"] to get the ip, and that seems to be correct, since it inserts the correct ip into the database I'm using.
Here is the call:
GetTimezone(Request.ServerVariables["REMOTE_ADDR"]);
You're getting an exception, probably because of a trust issue / firewall on the production server.
Get rid of the evil catch block so you can find out what the exception is.

What are some methods to link to and run a local .exe file in a local browser

I am trying to use html/javascript to run a local .exe file in a local browser. The .exe file will generate asci text and I have it programed to encapsulate the text in html legible to the browser. But I want to have it load the new output from the .exe in the current browser, replacing whats there now.
There are two solutions I can think of.
1) In IE - Use WScript.Shell and do whatever you need in Windows.
In IE - Here is a sample to open notepad.
You place your executable there and then have it write it's file and then read the file.
<script>
function go() {
w = new ActiveXObject("WScript.Shell");
w.run('notepad.exe');
return true;
}
</script>
<form>
Run Notepad (Window with explorer only)
<input type="button" value="Go"
onClick="return go()">
</FORM>
Here is a sample for reading from a file
// define constants
// Note: if a file exists, using forWriting will set
// the contents of the file to zero before writing to
// it.
var forReading = 1, forWriting = 2, forAppending = 8;
// define array to store lines.
rline = new Array();
// Create the object
fs = new ActiveXObject("Scripting.FileSystemObject");
f = fs.GetFile("test.txt");
// Open the file
is = f.OpenAsTextStream( forReading, 0 );
// start and continue to read until we hit
// the end of the file.
var count = 0;
while( !is.AtEndOfStream ){
rline[count] = is.ReadLine();
count++;
}
// Close the stream
is.Close();
// Place the contents of the array into
// a variable.
var msg = "";
for(i = 0; i < rline.length; i++){
msg += rline[i] + "\n";
}
// Give the users something to talk about.
WScript.Echo( msg );
2) Create a signed Java Applet and talk to it through JavaScript
Maybe there is a way to talk to a Java Applet from the Javascript and then have the Applet do the work - It would probably need to be signed.
The short answer: you can't do it without writing a browser plug-in of some sort. Probably there's a simpler way of doing what you want.
Would it make it easier if, rather than running the browser and application separately, maybe you had an application you run which contains a webbrowser - then talking between them is easier because you can get access to the inner workings of the browser ... Just a thought.

Categories