unable to display the last visited date - javascript
Following is the script that is meant to store the time,date the user last visited a webpage.But nothing happens when i run the HTML with the script.
window.onload = init;
function init() {
var now = new Date();
var last = new Date();
document.cookie = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toGMTString() + ";lastVisit=" + last.toDateString();
var lastVisit = document.cookie.split("=");
document.getElementById("lastVisitedOn").value = lastVisit[6];
}
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="lastVisitTester.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>
Why is the time/date not getting set for the h tag ? What is wrong with the script ?
window.onload = function () {
var now = new Date(),
expires = now,
lastVisit = document.cookie.match(/lastVisit=([^;]+)/),
userName = 'somebody';
// 1. You should set month in standalone way
expires.setMonth(now.getMonth() + 2);
// 2. For each cookie you set value individually: for username in 1st line, and for lastVisit in 2nd
document.cookie = "username=" + userName + ";path=/;expires=" + expires.toGMTString();
document.cookie = "lastVisit=" + now.toDateString() + ";path=/;expires=" + expires.toGMTString();
// 3. You should test and extract your cookie value BEFORE you set it (see above with cookie match)
// 4. You should test if it's not null also
if (null != lastVisit) {
// 5. You should use innerHTML property for set content
document.getElementById("lastVisitedOn").innerHTML = lastVisit[1];
}
// 6. But in general you should RTFM more :)
// 7. ps: And also use some standard frameworks for this -- not manual raw JS
}
Well there are some problems in your code.
As others has mentioned before:
The function "toGMTString()" is deprecated.
Use "toLocaleString()" or "toUTCString()" instead of "toGMTString()" (see also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#toGMTString)
You should use innerHTML and you had your index wrong.
You cannot use document.cookie that way. Not sure way.
Example:
var now = new Date();
var last = new Date();
var cookieText = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toLocaleString() + ";lastVisit=" + last.toDateString();
document.cookie = cookieText;
var lastVisit = cookieText .split("=");
document.getElementById("lastVisitedOn").innerHTML = lastVisit[4];
Related
Python requests module giving "Please enable JavaScript to view the page content" on local but working on AMI and Heroku server
import requests r = requests.get('https://my.cigna.com') print(r.text) When I run the above code on the local system It gives me below response(check last line) <!DOCTYPE html>\r\n<html><head>\r\n<meta http-equiv="Pragma" content="no-cache"/>\r\n<meta http-equiv="Expires" content="-1"/>\r\n<meta http-equiv="C acheControl" content="no-cache"/>\r\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>\r\n<link rel="shortcut icon" href="data:;bas e64,iVBORw0KGgo="/>\r\n\r\n<script>\r\n\r\n(function(){\r\nwindow["bobcmn"] = "11111110101010200000005200000005200000000251c47c46200000096300000000300 000000300000006/TSPD/300000008TSPD_101300000005https3000000b00832d38fa5ab2000bef1c6292d5d65850e93300734653e4ce2c59efe6632d24f66fbd7d1f0f1f7e1082c3139f f0a2800873fd1b935f9eeef417fa5c01bffa575ead6603ec35dcc40233cad0a332514761bee131cffbe1575200000000200000000";\r\n\r\nwindow.Cus=!!window.Cus;try{(functi on(){(function(){var z={decrypt:function(z){try{return JSON.parse(function(z){z=z.split("l");var s="";for(var _=0;_<z.length;++_)s+=String.fromCharCod e(z[_]);return s}(z))}catch(_){}}};return z={configuration:z.decrypt("123l34l97l99l116l105l118l101l34l58l34l110l111l34l44l34l100l101l98l117l103l103l10 5l110l103l34l58l34l110l111l34l44l34l109l111l100l117l108l101l49l34l58l34l101l110l97l98l108l101l100l34l44l34l109l111l100l117l108l101l50l34l58l34l101l110 l97l98l108l101l100l34l44l34l109l111l100l117l108l101l51l34l58l34l101l110l97l98l108l101l100l34l44l34l109l111l100l117l108l101l52l34l58l34l101l110l97l98l1 08l101l100l34l125")}})();\nvar Sz=44;try{var Iz,Jz,Lz=Z(118)?1:0,zZ=Z(358)?1:0,ZZ=Z(706)?0:1,sZ=Z(440)?1:0,SZ=Z(844)?0:1;for(var lZ=(Z(87),0);lZ<Jz;++ lZ)Lz+=(Z(870),2),zZ+=Z(279)?2:1,ZZ+=(Z(127),2),sZ+=Z(732)?1:2,SZ+=Z(198)?3:2;Iz=Lz+zZ+ZZ+sZ+SZ;window.zz===Iz&&(window.zz=++Iz)}catch(zs){window.zz=I z}var Ss=!0;function S(z,s){z+=s;return z.toString(36)}\nfunction _s(z){var s=93;!z||document[I(s,211,198,208,198,191,198,201,198,209,214,176,209,190, 209,194)]&&document[J(s,211,198,208,198,191,198,201,198,209,214,176,209,190,209,194)]!==S(68616527573,s)||(Ss=!1);return Ss}function Is(){}_s(window[I s[S(1086810,Sz)]]===Is);_s(typeof ie9rgb4!==S(1242178186155,Sz));_s(RegExp("\\x3c")[S(1372161,Sz)](function(){return"\\x3c"})&!RegExp(S(42845,Sz))[S(1 372161,Sz)](function(){return"\'x3\'+\'d\';"}));\nvar js=window[J(Sz,141,160,160,141,143,148,113,162,145,154,160)]||RegExp(I(Sz,153,155,142,149,168,14 1,154,144,158,155,149,144),J(Sz,149))[S(1372161,Sz)](window["\\x6e\\x61vi\\x67a\\x74\\x6f\\x72"]["\\x75\\x73e\\x72A\\x67\\x65\\x6et"]),Js=+new Date+(Z (476)?6E5:537525),zS,ZS,_S,IS=window[J(Sz,159,145,160,128,149,153,145,155,161,160)],jS=js?Z(845)?23770:3E4:Z(731)?6069:6E3;\ndocument[I(Sz,141,144,144 ,113,162,145,154,160,120,149,159,160,145,154,145,158)]&&document[I(Sz,141,144,144,113,162,145,154,160,120,149,159,160,145,154,145,158)](I(Sz,162,149,1 59,149,142,149,152,149,160,165,143,148,141,154,147,145),function(z){var s=15;document[I(s,133,120,130,120,113,120,123,120,131,136,98,131,112,131,116)] &&(document[I(s,133,120,130,120,113,120,123,120,131,136,98,131,112,131,116)]===S(1058781968,s)&&z[J(s,120,130,99,129,132,130,131,116,115)]?_S=!0:docum ent[J(s,133,120,130,120,113,\n120,123,120,131,136,98,131,112,131,116)]===S(68616527651,s)&&(zS=+new Date,_S=!1,JS()))});function JS(){if(!document[J(6 7,180,184,168,181,188,150,168,175,168,166,183,178,181)])return!0;var z=+new Date;if(z>Js&&(Z(175)?6E5:391380)>z-zS)return _s(!1);var s=_s(ZS&&!_S&&zS+ jS<z);zS=z;ZS||(ZS=!0,IS(function(){ZS=!1},Z(22)?1:0));return s}JS();var LS=[Z(100)?17795081:12388952,Z(902)?2147483647:27611931586,Z(659)?2147483647: 1558153217];\nfunction I(z){var s=arguments.length,_=[];for(var L=1;L<s;++L)_.push(arguments[L]-z);return String.fromCharCode.apply(String,_)}function oS(z){var s=73;z=typeof z===S(1743045603,s)?z:z[J(s,189,184,156,189,187,178,183,176)](Z(681)?21:36);var _=window[z];if(!_[I(s,189,184,156,189,187,178 ,183,176)])return;var L=""+_;window[z]=function(z,s){ZS=!1;return _(z,s)};window[z][J(s,189,184,156,189,187,178,183,176)]=function(){return L}}for(var z_=(Z(30),0);z_<LS[S(1294399161,Sz)];++z_)oS(LS[z_]);\n_s(!1!==window[J(Sz,111,161,159)]);window.OZ={ss:"080c2c1eda01800069124f1b5a83fc96fafe0a0dbc83 e2e583cf1f4bc9a341edae4a30a47d7c4b3813be508797f9bc851524c4d9baf10876ef1f1078d2e9eb2e566dd9b7b6a562958391630c37574b49bfc5623b576c20cd27c302ee516a176224 f2fbb00a43bff05b8edd78ac57568a9b648b2973acfc228913dee8be06ecf802d0499c07d98d5d"};function J(z){var s=arguments.length,_=[],L=1;while(L<s)_[L-1]=argume nts[L++]-z;return String.fromCharCode.apply(String,_)}function s_(z){var s=+new Date,_;!document[I(99,212,216,200,213,220,182,200,207,200,198,215,210, 213,164,207,207)]||s>Js&&(Z(129)?6E5:494155)>s-zS?_=_s(!1):(_=_s(ZS&&!_S&&zS+jS<s),zS=s,ZS||(ZS=!0,IS(function(){ZS=!1},Z(173)?1:0)));return!(argument s[z]^_)}function Z(z){return 481>z}\n(function i_(s){s&&"number"!==typeof s||("number"!==typeof s&&(s=1E3),s=Math.max(s,1),setInterval(function(){i_(s -10)},s))})(!0);})();}catch(x){\n}finally{ie9rgb4=void(0);};function ie9rgb4(a,b){return a>>b>>0};\n\r\n})();\r\n\r\n</script>\r\n\r\n<script type="te xt/javascript" src="/TSPD/0832d38fa5ab2000c3e644a33889f1e28c37ed3e7e11517eab4ec9c87769bb4e4892f69070fe1752?type=10"></script>\r\n<noscript>Please enab le JavaScript to view the page content.<br/>Your support ID is: 11583418831671342532.</noscript>\r\n</head><body>\r\n</body></html> but when I run it on my Heroku or AMI server it works fine and gives <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE></TITLE> <script> var bizrouter_uri = "/rte/public/validatetoken"; function getQueryStringValue (key) { return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")); } function setCookie(cname, cvalue, exhours) { var d = new Date(); d.setTime(d.getTime() + (exhours*60*60*1000)); var expires = "expires="+d.toGMTString(); var cook = cname + "=" + cvalue + ";" + expires + ";path=/"; document.cookie = cook; //document.cookie = cname + "=" + cvalue + "; " + expires + "; domain=" + document.domain + "; path=/"; } function postForm() { var myToken = getQueryStringValue("token"); //create the Token text cookie if (myToken) { setCookie("HW_TOKEN_TEXT", myToken, 1); document.webseal.action = bizrouter_uri; document.webseal.token.value = myToken; } else { setCookie("HW_TOKEN_TEXT", "", 0); } setCookie("HW_TOKEN_DNS", window.location.protocol + "//" + document.domain, 1); document.webseal.submit(); } </script> </HEAD> <body onLoad="postForm();"> <form name="webseal" method="post" action="/web/public/guest" > <input type="hidden" name="token" value="default" /> </form> </HTML> Not able to figure out, how to run it on local system. Any help will appreciable. NOTE: This is not regarding to "how to scrape JS content/how to scrape website with JS enabled". This is for if it is working on AMI and Heroku then why not working on local system
First of all, the response payload indicated the there is a F5 load-balancer between you and the web server 'https://my.cigna.com'. Because this is a known signature from F5: Please enable JavaScript to view the page content.<br/>Your support ID is: 11583418831671342532. Secondary, there is a way to bypass it by using a Javascript capable http client, such as Selenium + Chrome, as indicated by #Maaz: import time from selenium import webdriver import selenium.webdriver.chrome.service as service service = service.Service('/path/to/chromedriver') service.start() capabilities = {'chrome.binary': '/path/to/custom/chrome'} driver = webdriver.Remote(service.service_url, capabilities) driver.get('http://www.google.com/xhtml'); time.sleep(5) # Let the user actually see something! driver.quit() For implementation explanation, you can refer to this page: http://chromedriver.chromium.org/getting-started
Some pages (possibly Ajax?) take several steps to load. This ...<noscript>Please enable JavaScript to view the page content.<br/>Your support ID is: 11583418831671342532.</noscript>... is the initial page content which is then transformed into actual html. For my scraping endeavor, I used time.sleep(5) to let the page load before scrapping. So the order would be driver.get("https://google.com") time.sleep(5) print(driver.page_source)
I cannot change HTML with .innerHTML. keep getting message "cannot set innerHTML property of null"
My javascript to get the day and time and to place it in the div is as below: function print(message){ var div1= document.getElementById("date-and-time"); div1.innerHTML= message ; } function addZero(i) { if (i < 10) {i = "0" + i;} return i; } function todaysDate (){ var today= new Date(); var day= today.getDay(); var daylist=["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; var whatDayTime = "<p> Today is " + daylist[day] + ". </p>"; var hour= addZero(today.getHours()); var minute= addZero(today.getMinutes()); var second= addZero(today.getSeconds()); whatDayTime += "<p> The time is " + hour + ":" + minute+ ":" + second + ". </p>"; return whatDayTime; } print(todaysDate()); HTML looks like this: <!DOCTYPE html> <html> <head> <title>Practice JavaScript</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="date-and-time"> </div> <script src="practice.js"></script> </body> I keep getting the error message" cannot set property of innerHTML to null". help? Many thanks. i am a beginner.
date-and-time is class name not id. You should add id to element,use like this, <body> <div class="date-and-time" id="date-and-time"> </div> or change your function, use getElementsByClassName method, Look at this article. function print(message){ var div1= document.getElementsByClassName("date-and-time"); div1[0].innerHTML= message ; }
When looking for an element with an id, that element must exist. You used class instead of id. False: <div class="date-and-time"> </div> Right: <div id="date-and-time"> </div>
You need to select element by class instead of id using querySelector Replace var div1= document.getElementById("date-and-time"); by var div1= document.querySelector(".date-and-time");
date-and-time is class name and you are accessing it by ID. Either change attribute name to id or access element by class name or querySelector.
JavaScript: string use in dynamic HTML
I'm new to JavaScript and have an issue with passing a string to 'innerHTML' as part of the dynamic creation of an HTML document. Reason for this: I need to specify an image path and want to be able to output a different image onto the screen depending on the details retrieved from a cookie (i.e. the image path changes each time so that image = 1001.jpg, image = 1002.jpg etc, depending on the object details retrieved). At present, unless I hardcode the line: "<p><img src=\images/1005.jpg"\"</p>"; I don't get an output. I tried various ways of inputting a string into this line but no joy so far. My code is probably not the best, but it works, apart from the image issue: function changeMe(){ ... var studentObject = JSON.parse(getName); // info from cookie var path = studentObject.imagePath; // works: images/1005.jpg var res = path.charAt(10) //alert(res); // = 5, works var newPath = "<p><img src=\"images/1001.jpg\"></p>"; // I 'amend' the newPath string value: **var answer = newPath.substr(0, 23) + res + newPath.substr(25.26);** //alert(answer); // works: <p><img src=\"images/1005.jpg"\</p> var oPara = document.createElement('p'); oPara.style.fontFamily = "Arial sans-serif"; oPara.style.fontSize = "20px"; oPara.style.color = "#77787E"; oPara.style.fontWeight = "bold"; oPara.innerHTML = "<p><br>Name & Surname: " + studentObject.name + " " + studentObject.surname + "</p>" + answer; // doesn't work //"<p><img src=\\" + "\"" + path + "\"" +"></p>"; // this doesn't work either document.body.appendChild(oPara); } What am I missing here?
Is this example helps? <!DOCTYPE html> <html lang="en"> <head> <title> Bla! </title> <script type='text/javascript'> function AddStudent() { var studentData = { "name":"John Dou" }; // for the exmaple. var paragraph = document.createElement('p'); // set any style paragraph.innerHTML = "The student " + studentData.name + " added to the family"; document.body.appendChild(paragraph); } </script> </head> <body> <button onclick='AddStudent()'> Add Student </button> </body> </html>
How to display JS values on my HTML page
I'm trying to get three different dynamic timezone clocks on my site. i've got the following js code which i found on this site (saved as myClocks.js and included on the header of my html site): var clock1 = new Date(); var clock2 = new Date(); var clock3 = new Date(); clock2.setHours(clock2.getHours() + 3); clock3.setHours(clock3.getHours() - 5); clock1.getUTCHours(); clock1.getUTCMinutes(); clock1.getUTCSeconds(); clock2.getUTCHours(); clock2.getUTCMinutes(); clock2.getUTCSeconds(); clock3.getUTCHours(); clock3.getUTCMinutes(); clock3.getUTCSeconds(); How do I code the "display" to show it anywhere I want on my HTML page? For example as an id called clocks, to look like the following: New York: 02:12:02 Paris: 17:01:24 Moscow: 22:23:42 Many thanks in advance.
<html><head></head><body> <script language="javascript"> ourDate = new Date(); document.write("The time and date at your computer's location is: " + ourDate.toLocaleString() + ".<br/>"); document.write("The time zone offset between local time and GMT is " + ourDate.getTimezoneOffset() + " minutes.<br/>"); document.write("The time and date (GMT) is: " + ourDate.toGMTString() + ".<br/>"); </script> </body></html>
innerHTML is what you need. Try something like: window.onload = function(){ // It is important to wait till DOM is ready! var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds(); document.getElementById("clocks").innerHTML = clocks_str ; } And if you want it dynamic , use setInterval method , like this: var clocks_interval; var clocks_box; window.onload = startClocks; function startClocks(){ clocks_box = document.getElementById("clocks"); clocks_interval = setInterval(updateClocks , 1000); // 1000 means 1 second } function updateClocks (){ var clocks_str = clock3.getUTCHours()+" "+ clock3.getUTCMinutes()+" "+clock3.getUTCSeconds(); clocks_box.innerHTML = clocks_str ; }
You can create a div or other HTML and use "innerHTML". document.getElementById("clocks").innerHTML = clock1.getUTCHours();
Setting multiple cookies in Javascript
I'm trying to set multiple cookies in document.cookie, but unfortunately only one is getting added. I know there are multiple examples present on the 'Net for setting up these kind of cookies,and I followed one of them. But still I'm unable to set that out. I followed this link to set my cookie. My Code: function setCookie(start_time,end_session_time,total_time,flag,count){ var cookie_string = "start_time="+start_time;; if(end_session_time) { cookie_string +="; end_session_time="+end_session_time; } if(total_time){ cookie_string +="; total_time="+total_time; } if(flag){ cookie_string +="; flag="+flag; } if(count){ cookie_string +="; count="+count; } document.cookie =cookie_string ; console.log(cookie_string); console.log("document.cookie ="+ document.cookie); } The Output: cookie_string :: start_time=1369926508266; flag=1; count=1 document.cookie =start_time=1369926508266;
Adding a cookie is performed via document.cookie = "name=value" to add multiple keys, you should perform multiple assigments function setCookie(start_time, end_session_time, total_time, flag, count) { document.cookie = "start_time=" + start_time; if (end_session_time) { document.cookie = "end_session_time=" + end_session_time; } if (total_time) { document.cookie = "total_time=" + total_time; } if (flag) { document.cookie = "flag=" + flag; } if (count) { document.cookie = "count=" + count; } console.log("document.cookie = " + document.cookie); }
Cookies are key value pairs (with some optional additional info added on, like the expiry date). To set more than one, you just set document.cookie more than once. The ; separator is used to specify the additional info, not to add more different cookies.
There you go a sample example to add, list and delete multiple cookies <!DOCTYPE html> <html> <head> <script> var n=1; function addCookie(){ document.cookie=n+"="+n;n++; } function ListCookies(){ var result = document.cookie; document.getElementById("p").innerHTML=result; } function removeCookies(){ //document.cookie=""; var result = document.cookie; var cookieArray = result.split(";"); for(var i=0;i<cookieArray.length;i++){ var keyValArr = cookieArray[i].split("="); document.cookie=keyValArr[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; } } </script> </head> <body> <button onclick='addCookie()'>ADD COOKIE</button><br> <button onclick='ListCookies()'>LIST COOKIES</button> <button onclick='removeCookies()'>REMOVE COOKIES</button> <h1>RESULT:</h1> <p id="p"></p> </body> </html>