im trying to create a cookie while using socket.io. I am able to read cookies but cannot find any information on how to create one.
socket.on('test', async function(){
// view set cookies (works!)
console.log('cookies', socket.handshake.headers.cookie);
// create cookie here...
});
thank you
you could set a cookie like you could do it in the mdn documentation with setcookies() and read it with the cookies api
You can do it the same way as document.cookie, but instead of:
document.cookie = ";mycookie=myval";
you do:
socket.handshake.headers.cookie = ";mycookie=myval; expires=cookieDate; path=cookiePathOnWebsite"
for example:
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
socket.on('test',async function(){
socket.handshake.headers.cookie = ";foo=bar; expires="+date+";path=/"
});
would set a cookie at the main page of your website, with foo defined as bar!
Related
I need to find the way to keep the parameters in the url upon navigation if they are entered once, ie: ?aff=john
So for example, user comes to website.com/?aff=john and navigates to about-us I need to make that url parameters are kept, so the full website name is: website.com/about-us/?aff=john
This is what I've tried so far, but it is not working.. it keeps adding the url parameters (window.location.search)
var params = false
var baseUrl = ''
var currUrl = window.location.href
if (window.location.search != '') {
params = true
}
if (params) {
baseUrl = currUrl + window.location.search
window.location.href = baseUrl
}
Thanks.
EDIT: already tried proposed.. not working.
You can use sessionStorage to save navigation data into a key. Pick it up whenever required. Now-a-days, all browsers support it except Opera mini.
Hopefully, your software does not have browser constraints and your application does not have to work on outdated browsers.
As copied from mozilla site, code to use sessionstorage would be like :
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove a key from sessionStorage
sessionStorage.removeItem('key');
// Remove all data from sessionStorage
sessionStorage.clear();
This way, you won't need to append it on every page. For the domain url and in current browser session, you can get it from sessionStorage.
You can save the query string using window.location.search and then you can add link handler in using jQuery like below:
var glString = window.location.search;
$('a').on('click', function(evt) {
evt.preventDefault();
window.location = $(this).attr('href') + glString;
});
or if you prefer javascript
var glString = window.location.search;
var links = document.getElementByTagName('a');
links.addEventListener('click', function(evt) {
evt.preventDefault();
window.location = $(this).attr('href') + glString;
});
You can temporary save the previous url using sessionStorage.
sessionStorage.setItem('parameter', 'dataString');
sessionStorage.getItem("parameter");
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;
}
These are my cookies:
My cookies
I'm running my website from my own computer using a WAMP server. I access my main page from http://127.0.0.1/Zulaijen/, and this is the javascript funcion to set the cookies (User and Session):
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "; expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + expires;
}
When I read them using javascript, it works fine. I get my session. Then I go to another PHP page named 'uploader.php' with this code:
if(!isset($_COOKIE['TestCookie']))
setcookie("TestCookie", "Hello World!", time()+3600);
print_r($_COOKIE);
echo("Session: " . $_COOKIE['Session'] . "<br/>User: " . $_COOKIE['User'] . "<br/>");
And the result is:
Array ( [TestCookie] => Hello World! )
Notice: Undefined index: Session in D:\wamp\www\Zulaijen\uploader.php
on line 30
Notice: Undefined index: User in D:\wamp\www\Zulaijen\uploader.php on line 30
Which means my PHP code is not reading the cookies I set with javascript. It only reads the one I set with my PHP code (TestCookie). And I don't understand why. They are within the same domain and the same path.
You should try setting cookie path. Could be that the cookie paths for PHP and JavaScript isn't matching, hence the cookie will not be shared between the two.
JavaScript cookie path:
How do I set path while saving a cookie value in JavaScript?
PHP coookie path (see path section):
http://php.net/manual/en/function.setcookie.php
I finally found out what was causing the problem (by accident). It's very confusing, but it has a very simple solution.
In order to read the cookies from PHP, you must read them from the very beginning of the file.
Doing this:
<?php print_r($_COOKIE); ?>
At the very beginning of the file (before any HTML code) prints every cookie I set correctly as it should. Even if you set them from PHP, if you don't do it from the very beginning of the file you won't be able to get them.
The reason why I was able to read the one I was setting with PHP was simply because I was setting it right before reading it, or so it seems.
I have a javascript cookie which works although I have pages in different directories. The cookie set on the default page has a path "/" while the cookie set in another directory has a path "/example"
I know many people have asked this many times but I can't do it by myself. I made a cookie code that actually works from the past three months. I don't want to mess it up. Can anyone help me add a set path "/" to my cookie code? Thanks in advance.
My code is:
<script language="JavaScript">
function SetCookie(cookieName,cookieValue) {
var today = new Date();
var expire = new Date();
var nDays=365
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
</script>
Indicate the path by adding the following to the end of the cookie string in function "SetCookie":
"; path=/";
http://www.quirksmode.org/js/cookies.html#doccookie
I am new to JavaScript and I need one simple solution.
How to save two text box from first html page, and show it in another html page.
Use localStorage: http://jsfiddle.net/usNwP/. localStorage is an object of which the values persist among pages on the same domain (so also after reloading, navigating or even rebooting the computer).
document.getElementById('save').onclick = function() {
// save values into localStorage
localStorage['input1'] = document.getElementById('input1').value;
localStorage['input2'] = document.getElementById('input2').value;
};
// load textboxes from localStorage (can be on another page)
document.getElementById('input1').value = localStorage['input1'] || "";
document.getElementById('input2').value = localStorage['input2'] || "";
All you need to know about using cookies with JavaScript:
http://www.quirksmode.org/js/cookies.html
A few practical functions to interact with cookies easier (for example set a cookie in one page, get a cookie in another):
http://www.w3schools.com/js/js_cookies.asp