I am using AngularJS client-side application and working with date and time. My problem is that local system date anyone can change, to protect this I want to use server date without any get or post request. Is there any way to get server date using JavaScript?
If you are running JavaScript at the client-side, the only way to find the server time is asking the server what is the current time. There is no magic here. You need to make a request to the server.
Options:
Use AJAX or Fetch.
If the HTML page is rendered in the server, you can write the current time during the page render and send it to client.
Please, note that it is not possible to have a precise time of the server due to network delays, but you can get pretty close using the code from this answer (modified):
var offset = 0;
function calcOffset() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://stackoverflow.com/", false);
xmlhttp.send();
var dateStr = xmlhttp.getResponseHeader('Date');
var serverTimeMillisGMT = Date.parse(new Date(Date.parse(dateStr)).toUTCString());
var localMillisUTC = Date.parse(new Date().toUTCString());
offset = serverTimeMillisGMT - localMillisUTC;
}
function getServerTime() {
var date = new Date();
date.setTime(date.getTime() + offset);
return date;
}
Related
Is there a way in either Javascript or C# to tell if the browser that someone is using has disabled caching of static content?
I need to be able to test whether or not the browser is optimized for caching.
UPDATE
I did a bit more investigation of the problem and you can find more detailed answer in my recent post
Note, the solution described below (initially) is not cross browser solution.
Not sure if it helps, but you can try the following trick:
1. Add some resource to you page, let's say it will be javascript file cachedetect.js.
2. The server should generate cachedetect.js each time someone request it. And it should contain cache-related headers in response, i.e. if browser's cache is enabled the resource should be cached for long time. Each cachedetect.js should look like this:
var version = [incrementally generated number here];
var cacheEnabled; //will contain the result of our check
var cloneCallback;//function which will compare versions from two javascript files
function isCacheEnabled(){
if(!window.cloneCallback){
var currentVersion = version;//cache current version of the file
// request the same cachedetect.js by adding <script> tag dynamically to <header>
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "cachedetect.js";
// newly loaded cachedetect.js will execute the same function isCacheEnabled, so we need to prevent it from loading the script for third time by checking for cloneCallback existence
cloneCallback = function(){
// once file will be loaded, version variable will contain different from currentVersion value in case when cache is disabled
window.cacheEnabled = currentVersion == window.version;
};
head.appendChild(script);
} else {
window.cloneCallback();
}
}
isCacheEnabled();
After that you can simply check for cacheEnabled === true or cacheEnabled === false after some period of time.
I believe this should work: http://jsfiddle.net/pseudosavant/U2hdy/
Basically you have to preload a file twice and check how long it took. The second time should take less than 10ms (in my own testing). You will want to make sure the file you are testing is sufficiently large that it takes at bit to download, it doesn't have to be huge though.
var preloadFile = function(url){
var start = +new Date();
var file = document.createElement("img");
file.src = url;
return +new Date() - start;
};
var testFile = "http://upload.wikimedia.org/wikipedia/en/thumb/d/d2/Mozilla_logo.svg/2000px-Mozilla_logo.svg.png"
var timing = [];
timing.push(preloadFile(testFile));
timing.push(preloadFile(testFile));
caching = (timing[1] < 10); // Timing[1] should be less than 10ms if caching is enabled
Another approach that involves client and server.
Make a call to a page/endpoint, which will set a random unique id in response. Set the cache header for this page/endpoint
Make the same call again, which will set a different unique number
If the the numbers match it is coming from cache or it is coming from server
I wrote a script on the Jmeter Web Driver in javascript and Java .
On a Windows system , the script is running perfectly . But on a Linux System , i have a weird problem . The lastmodifed then i obtain is not good. front_end.jtl has been modified yesterday , but the script say today at 10:00 in milliseconds timestamp .
Please help me.
// Importing packages (and all classes in package) from Java into Javascript var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
// We don't use wait in this very simple test, but here is way to access for more realistic testing
var wait=new support_ui.WebDriverWait(WDS.browser, 5)
// Start recording the time for this request
WDS.sampleResult.sampleStart();
// Let's get a page
var baseUrl = "cnyw${FE}.mycore.core-cloud.net"
WDS.browser.get("https://"+ baseUrl)
var frontjtl = new java.io.File('/home/mycore/front_end.jtl')
var frontlog = new java.io.File('/home/mycore/jmeter_front_end.log')
var lastmodifjtl = frontjtl.lastModified()
var lastmodiflog = frontlog.lastModified()
if ( lastmodifjtl = lastmodiflog ) {
var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
screenshot.renameTo(new java.io.File('/home/mycore/screenshots/tools/screenshot_cnyw${FE}.png'))
}
// Record the time of the request
WDS.sampleResult.sampleEnd();
I would recommend using Files.getLastModifiedTime() instead, something like:
var lastmodifjtl = java.nio.file.Files.getLastModifiedTime(java.nio.file.Paths.get(frontjtl.toURI()))
should do the trick for you.
Just in case see The WebDriver Sampler: Your Top 10 Questions Answered article for more information
I found an explanation : https://bugs.openjdk.java.net/browse/JDK-8177809
It's a confirmed bug ...
i have rewrite the script in Java directly. All is okay now.
I try to schedule a script using the 'Scheduled Tasks' in ML8. The documentation explains this a bit but only for xQuery.
Now I have a JavaScript file I'd like to schedule.
The error in the log file:
2015-06-23 19:11:00.416 Notice: TaskServer: XDMP-NOEXECUTE: Document is not of executable mimetype. URI: /scheduled/cleanData.js
2015-06-23 19:11:00.416 Notice: TaskServer: in /scheduled/cleanData.js [1.0-ml]
My script:
/* Scheduled script to delete old data */
var now = new Date();
var yearBack = now.setDate(now.getDate() - 65);
var date = new Date(yearBack);
var b = cts.jsonPropertyRangeQuery("Dtm", "<", date);
var c = fn.subsequence(cts.uris("", [], b), 1, 10);
while (true) {
var uri = c.next();
if (uri.done == true){
break;
}
xdmp.log(uri.value, "info"); // log for testing
}
Try the *.sjs extension (Server-side JavaScript).
The *.js extension can be used for static JavaScript resources to return to the client instead of executed on the server.
Hoping that helps,
I believe that ehennum found the issue for you (the extension - which is what the mime-type error is complaining about.
However, on the same subject, not all items in ML work quite as you would expect for Serverside Javascript. For example, using sjs as a target of a trigger is (or recently) did not work. So for things like that, it is also possible to wrap the sjs call inside of xqy using xdmp-invoke.
I'm trying to implement a JSON call to simulate AJAX on a certain page where an AJAX panel isn't a viable option.
I want call my .aspx page when a State is selected from a drop down and populate the Counties drop down.
in my State dropdown, I have this call:
onchange="jsonDropDownLoader('COUNTIES', this, 'Content2_DDLCounties')"
That call is on the page and the code is here:
function jsonDropDownLoader(sType, oParent, oChild) {
var lstrChild = document.getElementById(oChild);
var lstrFilter = ""
if (oParent.value > "") {
lstrFilter = oParent.value
}
lstrChild.options.length = 0;
if (oParent.value > "") {
var JSONobject = {};
var http_request = new XMLHttpRequest();
url = "/AltairWeb.NET/RS/jsonDropDownLoader.aspx?TYPE=" + sType + "&FILTER=" + lstrFilter
http_request.open("GET", url, false);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
JSONobject = JSON.parse(http_request.responseText);
}
};
http_request.send(null);
var JSONarray = eval('(' + http_request.responseText + ')').data
for (var i = 0; i < JSONarray.length; ++i) {
var optn = document.createElement("OPTION");
optn.text = JSONarray[i].text;
optn.value = JSONarray[i].value;
lstrChild.options.add(optn);
}
}
}
It returns a string which I then use to populate the County drop down.
I'm getting data back, but it's not rendering on your QA server. Using the developer tools with IE8, I can see that I have a error on this line:
JSONobject = JSON.parse(http_request.responseText);
it says that JSON is not declared.
It says I also have a syntax error on this line:
var JSONarray = eval('(' + http_request.responseText + ')').data
This works perfectly on my development box. However, my development box has WinXP / IIS 5 on it, whereas, our QA server is a Win2008 server with IIS7.5. We have new development boxes coming, but until then, I'm stuck with the XP machine.
Since it works locally, it seems like it must be a security issue with either Windows or IIS on the QA server, possibly with the http_request call, but I can't find anything via google that has helped me figure this out.
I know I've seen posts that JSON.parse is not supported by IE prior to IE9, but this works perfectly in IE8 when I point to my dev server, but not when I point to the QA server, so it doesn't seem to be a browser issue.
Any ideas?
JSON.parse() is a function of your browser, not the server.
Are you sure the difference is the server ... and not your client browser???
You might also wish to consider using something like jQuery (which can both simplify your coding, and help mediate cross-browser issues like this). for example:
Parse JSON in JavaScript?
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
First, you are using a synchronous call (xhr.open('GET', url, false)) , and you are also using onreadystatechange . This is wrong. Choose one or the other.
https://developer.mozilla.org/en/xmlhttprequest
Next, check your browser support for JSON. See https://stackoverflow.com/a/891306/48082 .
If you are unsure, then use json2.js from json.org.
Finally, do not use eval. Use a proper JSON library.
I need to obtain current time (from a credible source) using JSON. Precise time is mission-critical in my application so I cannot rely on the time of the device, even if it is only a second or two off.
EDIT: I am not as worried about 'precision' rather just so that several devices running the app have the same time.
As of Jan. 07th 2020 http://worldtimeapi.org/ is working fine. we can get current date and time details for specfic time-zone or ip address easily in either json format or plain text format.
http://worldtimeapi.org/api/timezone/America/Santiago
the above url will give you the current date and time details in json for "America/Santiago".
http://worldtimeapi.org/api/timezone/Asia/Kolkata
the above url will give you the current date and time details in json for "Asia/Kolkata".
Request the current time based on your public IP (as JSON):
$ curl "http://worldtimeapi.org/api/ip"
Note: by default, the API returns JSON. Adding a suffix of .txt to any API URL will return a plain-text response, which may be easier to parse on some systems.
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
// This is where you do whatever you want with the time:
alert(time);
});
from here
As of Sept. 12th 2015 http://www.timeapi.org/utc/now.json seems to be working.
{"dateString":"2015-09-12T23:15:56+01:00"}
More information here http://www.timeapi.org. It's hosted on Heroku and the source is on Github.
The worldtimeapi.org is working just fine. If you will be using Javascript:
const zone = 'Europe/Lisbon'
fetch('https://worldtimeapi.org/api/timezone/' + zone)
.then(r => r.json())
.then(r => {
// strip out timezone offset from datetime ISO string
const d = new Date(r.datetime.replace(/[+-]\d\d:\d\d$/, ''))
console.log(`Time now in ${zone}: ${d.getHours()}:${d.getMinutes()}`)
})