How to get timezone before postback - javascript

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.

Related

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";

Javascript random redirect

so my situation is as follows:
I wrote a submission system in php that writes to a textfile rather than a database, the idea of the system is people submit their url to the textfile and then when that script is called on a page, it redirects to a random address out of the textfile; the problem is, I don't know how to make javascript read from the text file and then pick a line to redirect to.
Actually, just to clarify, I know how to make javascript read from the text file; but I have NO idea how id write a function to pick a url from the file and forward to it.
Seeing as I hit this road block a couple of days ago, the only way I have been handling submissions is checking the text file every 12 hours for new submissions and then manually adding them to this code:
setTimeout(function() {
var howMany = 38;
var page = new Array(howMany+1);
page[0]="http://gproxy.nl/";
page[1]="http://homeproxy.me/";
page[2]="http://proxyturbo.com/";
page[3]="http://www.lblocker.info/";
page[4]="http://goprivate.eu/";
page[5]="http://jsproxy.com/";
page[6]="http://openthis.eu/";
page[7]="http://proxy4home.info/";
page[8]="http://dedicatedipaddress.net/";
page[9]="https://www.4everproxy.com/";
page[10]="http://www.surfsearch.info/";
page[11]="http://www.leaveproxy.com/";
page[12]="http://proxyecole.fr/";
page[13]="http://newipnow.com/";
page[14]="http://www.hiddenmode.info/";
page[15]="https://europrox.org/";
page[16]="https://www.4everproxy.com/";
page[17]="https://goingthere.org/";
page[18]="http://xuxor.com/";
page[19]="http://033b.com/";
page[20]="http://thewebtunnel.com/";
page[21]="http://prox.phanteye.com/";
page[22]="http://www.hiddenall.info/";
page[23]="http://www.5966.info/";
page[24]="http://hideyoself.com/";
page[25]="http://prox.phanteye.com/";
page[26]="http://freevideoproxy.com/";
page[27]="http://thewebtunnel.com/";
page[28]="http://openthis.eu/";
page[29]="https://europrox.org/";
page[30]="http://xuxor.com/";
page[31]="https://incloak.com/";
page[32]="http://www.leaveproxy.com/";
page[33]="http://www.openunblocker.com/";
page[34]="http://post48.com";
page[35]="http://post48.com";
page[36]="http://inteproxy.com";
page[37]="http://208.73.23.59";
page[38]="http://hidemetoday.com/";
function rndnumber(){
var randscript = -1;
while (randscript < 0 || randscript > howMany || isNaN(randscript)){
randscript = parseInt(Math.random()*(howMany+1));
}
return randscript;
}
quo = rndnumber();
quox = page[quo];
window.location=(quox);
}, 1500);
I would be very grateful if someone would help me write the script or tell me what kind of function I should be googling to look up, googling "How to make javascript read from a textfile and redirect" doesn't really turn up much ; (
Many thanks!
If I understand correctly, first, you'll need a regex to find the URLs in the file. I would refer to this SO post for that: regular expression for url
Once you have that, you can go to any URL with window.location.href = 'http://google.com';
So, you'll do something like this...
var urlPattern = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/g;
var urls = data.match(urlPattern);
if (urls) {
window.location.href = urls[7];
}
Is that what you're looking for?
Or you can use a more simple regex like var urlPat = /https?:\/\/[^'"]+/g
Remember to use the /g flag with your regex to get all occurrences of the urls.

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

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

Can you pass URL parameters to a Javascript file?

<script src="myscript.js?someParameter=123"></script>
From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?
Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.
There are two ways to pass parameters to another JavaScript file:
As #Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.
Jquery Address does this, so i've been checking their code out and this is the improved solution I just created myself:
$.each($('script'), function(id, val){ //loop trough all script-elements
var tmp_src = String($(this).attr('src'));//store the src-attr
var qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index
//Check if the script is the script we are looking for and if it has QS-params
if(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
{
//this is myscript.js and has a querystring
//we want an array of param-pairs: var1 = value1, var2 = value2, ...
var params_raw = tmp_src.substr(qs_index + 1).split('&');
//create empty options array
var options = [];
//loop troug raw params
$.each(params_raw, function(id, param_pair){
//split names from values
var pp_raw = param_pair.split('=');
//store in options array
options[pp_raw[0]] = pp_raw[1];
});
//check the results out in the console!
console.log(options);
}
});
I hope this does what you need?
The answer is a definite "YES". I've been doing this on various projects for over a decade. The solution is actually easy, it's just non-intuitive (you have to generate an error). To be clear, the following code lets you do something like this:
<script src="https://example.com/script.js?id=1&bar=this works!" />
All you need to do is initiate a silent error, which takes less than 1/1000 of a second even on the worst outdated mobile browsers. You shouldn't do it a ton, but you only need to do it once. This error is processed, so it won't show up as an error in telemetry or 3rd party error trackers either.
// Generic function used to see if a param exists in a URL string.
// Provided here in case you don't know how to do it.
// This is not needed for the solution.
function getParameter (name, url) {
if (!url) url = scriptName()
name = name.replace(/[\[\]]/g, '\\$&')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
var results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
// Gets the name of this script (whatever this file runs in)
// You can use this name to get parameters just like you would for the window URL :)
function getScriptName () {
var error = new Error(),
source,
lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/),
currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/)
if ((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] !== '')
return source[1]
else if ((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1]
else if (error.fileName !== undefined)
return error.fileName
}

Change query argument of jQuery suggest plugin

This question is kind-of crappy because I try to get around some limitations:
Current JS sends an ajax query with the following code
jQuery('#searchbox').suggest('/?live=1');
What the server get is the following query string:
?live=1&q=searchstring
Problem:
The server expects the query string to be preceded with 's=' not 'q='
I have to use the existing scripts so what I'm trying to so is find a way to change 'q=' to 's=' in javascript, without altering the exisiting suggest plugin or the php search script.
Thanks.
The only way you will do that is by modifying the plugin, if you want to avoid changing the script forever and need this only for one page, override the function temporarily.
$.suggest.suggest = function() {
var q = $.trim($input.val());
if (q.length >= options.minchars) {
cached = checkCache(q);
if (cached) {
displayItems(cached['items']);
} else {
//This is the line we r changing
$.get(options.source, {s: q}, function(txt) {
$results.hide();
var items = parseTxt(txt, q);
displayItems(items);
addToCache(q, items, txt.length);
});
}
} else {
$results.hide();
}
}

Categories