Javascript/Rails Cookie not saving on safari but works on chrome - javascript

I am developing a rails app (I am a student) and I am trying to make a cookie that stores the users location which is found through the javascript geo location api. However, the cookie works perfectly in chrome but not safari or Firefox. I looked in the inspector and the cookie was there for chrome but not the other two. The code for the cookie is below. The rest of the code is written in ruby. The point of the cookie is so that I can get the users recent location in the controller.
<%if #lat_lng.nil? %>
<script>
getGeoLocation();
function getGeoLocation() {
navigator.geolocation.getCurrentPosition(setGeoCookie);
}
function setGeoCookie(position) {
var expiration = new Date();
expiration.setDate(expiration.getDate()+1);
var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
document.cookie = "lat_lng=" + escape(cookie_val); expires= 'expiration.toGMTString()';
}
</script>
<% end %>
The cookie is defined in my applications controller:
#lat_lng = cookies[:lat_lng]
I really appreciate any help that is possible!

When you are setting the cookie, it should be in the following format:
document.cookie = "some=value; expires=Mon, 1 Jan 2000 12:59:59 GMT";
In your case, you are simply defining a variable in javascript. Try changing it to:
document.cookie = "lat_lng=" + escape(cookie_val) + "; expires=" + expiration.toGMTString();
PS. However, the expires part is optional and should work without it just fine. Maybe, Safari and FF require it for security reasons? Try googling that.

Related

I have a wordpress site where a cookie is set determining what image/text to show on the front page. It works on mac always, on windows rarely

In snippets plugin, I have added the following code ;
add_action( 'wp_head', function () { ?>
<script>
function createCookie(cookieName,cookieValue,daysToExpire) {
var date = new Date();
date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + "; path=/; domain=humanistperspectives.org; secure";
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
function getCookie(cookieName) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [key,value] = el.split('=');
cookie[key.trim()] = value;
})
return cookie[cookieName];
}
function delCookie(cookieName) {
cookieValue = "";
var date = new Date();
date.setTime(date.getTime()-(3600));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + "; path=/; domain=humanistperspectives.org; secure";
}
</script>
<?php } );
This sets a cookie and sets the file and title that displays on the front page of our site.
When I inspect the same page in browsers on my mac (safari, firefox, chrome), I see that the cookies are all set, expiring in september of this year.
Here are the values of the cookie:
Name: issuecover
Value: /wp-content/uploads/2022/03/220.jpg
Domain: .domain.org
Expires: Sept 5, 2022
Size: 45
HttpOnly: false
Secure: true
Samesite: None;
Last accessed: Tue, May 17, 2022
The same values appear in Windows in firefox, chrome and edge — but in Windows, despite having the same cookie values, the site doesn't seem to be able to access the cookies. So the magazine cover is a blank image and the title is blank, etc — but I see when I inspect that yes, in fact, the cookie is set just like on my mac.
It's just that on the mac, every browser is able to access the values and display the appropriate text/image and on windows, the same cookies are not accessible to the browsers.
Does anyone know if Windows is more picky regarding cookies?
NOTE: the site is on Cloudflare and strangely, if I purge the cache and force refresh in windows, the information in the cookie is accessible to the browsers.. but only at that time. If I come back a few hours later... despite seeing the cookies being still active in the browsers, the information in the cookies won't display on the page after the first time.
I appreciate any help here..thanks very much!
EDIT: I added code to add SameSite=Lax and on Mac, that shows up, but on Windows, SameSite=None still.
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + "; path=/; domain=domain.org; secure; SameSite=Lax;";
UPDATE:
ACTUALLY, I noticed there was a javascript error from another plugin and when I removed it, and purged the cache, the cookie's samesite lax status actually transferred over in Windows and the cookies were readable/accessible on the page. However, the true test is to check back in 1-2 hours and see if it's still behaving how I want. I'll come back with the details. THANKS.
BAD NEWS :
So going back to the site, the cookies AGAIN, despite being there, with samesite=lax, are somehow not accessible to the page and their values can't display.
httponly is false... it SHOULD show up. Why is this not working in Windows? Both Mac and Windows have the cookies properly stored but only on Mac do they appear on the page. HELP!
FINAL UPDATE
I've removed the cookies and used global variables to select different issues and relevant content.
For some reason, it seems like Cloudflare is caching cookies.
So thanks for your help everyone!
I removed all cookie-related code and ended up with a much simpler and faster code with global variables.
Thanks everyone!

Use javascript to delete all cookies not working

On a HTML page I use this javascript code to set cookies
this.store.setItem = function(name, value) {
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires;
};
I am trying to create a function that delete all cookies potentially set through the previous function. I found different threat about clearing cookies using javascript... This is an example of code that I have tested
deleteAllCokies : function() {
var res = document.cookie;
var multiple = res.split(";");
for(var i = 0; i < multiple.length; i++) {
var key = multiple[i].split("=");
document.cookie = key[0]+" =; expires = Thu, 01 Jan 1970 00:00:00 UTC";
}
}
The code works perfectly on computer running uptodated browsers. However when I try the code on older Browser( I runned the page as a webOS app) I get an error while trying to delete the cookies
SecurityError: DOM Exception 18: An attempt was made to break through
the security policy of the user agent.
Someone has an idea about the problem?
The other browser may have other cookies created by other sources that your script doesn't have permission to delete. Try to dump all the cookies in the console.log to verify this.
I've saw this error in webos 1.x and 2.x. If your application is stored locally (built-in the ipk) the protocol to access the document is forced file:// by the OS. You can check this thread
LG recommends to use webStorage or serve your app by a webserver
PS: A hosted web app will use the HTTP/HTTPS protocol to access the document

How can I store persistent data with JS/JQuery using the file:/// protocol and IE/Edge browser?

I'm currently writing a small web page application where users can dynamically drag and drop links to files and pages on a customisable homepage.
It is written in Html5 and Javascript/Jquery mobile. The page will be stored on the local machine and accessed with the 'file:///' protocol, using the Internet Explorer / Microsoft Edge webbrowser.
I'm trying to find a way to store the data that resembles the customized page and links, so that when the user opens the page again the links will still be there and can be edited and customized further.
So far I've been looking into HTML localStorage, but this doesn't work with IE/Edge through the 'file:///' protocol, the page will not be hosted.
I was thinking of just creating a file with all the data in there, but I don't believe that is possible either due to security reasons.
I have not alot of experience with javascript, so any help is appreciated!
If you only want it to work on Internet Explorer/Microsoft Edge, a simple way to persist data would be using cookies. They will work even using the file:// protocol, and the only thing would be setting a far away expiration date (in the example below: 2/2/2222).
Try this sample code (part of it comes from this site) that will count the number of times a page has been loaded. Notice how the counter is kept even after closing the browser and reopening it:
<!doctype html>
<html>
<head>
<title>Persistent Data With Cookies In IE</title>
</head>
<body>
Number of reloads: <span id="num">-</span>
<script>
function setCookie(name, value)
{
var expiry = new Date(2222,2,2);
document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var cookieVal = getCookie("num");
var num = cookieVal != null ? cookieVal : 0;
document.getElementById("num").innerHTML = num;
setCookie("num", parseInt(num) + 1)
</script>
</body>
</html>
Pros of this solution:
Simple and easy to implement.
Works with the file:// protocol in IE and Edge (as specified in question) and also in Firefox.
Cons of this solution:
Limited storage space.
Doesn't work with the file:// protocol in Chrome (not required in question).

Cookie not being set in Safari, ios but works in ie, ff, chrome

I was alerted that when items are placed in our shopping cart using safari/ios, they are not showing up. The cart cookie is not being set. It is set by a redirect page. I saw the issue about safari not setting a cookie and redirecting, but if I take out the redirect, it is still not getting set. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>
<script type="text/javascript">window.onload= function() {
SetCookie('RORDERID','OECLICK*17180*39521',10);
setTimeout("redir()",100);}
function redir(){window.location = 'http://www.shopthethirdfloor.com/forward-to-ttf-cart.html';}
function SetCookie(cookieName,cookieValue,nDays) {var today = new Date();var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();}</script>
</head>
<body><br>If you are not redirected to the shopping cart, click here</body></html>
I thought maybe the setTimeout would allow it to work, but if I take out the call to redir() it still does not set the cookie.
Any suggestions?
Additional notes: I found a posting about this, and updated the code to:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>
<script type="text/javascript">window.onload= function() {
setCookie2('RORDERID','OECLICK*17180*43',10,'','','');
//setTimeout("redir()",100);
}
function redir(){window.location = 'http://www.shopthethirdfloor.com/forward-to-ttf-cart.html';}
function setCookie2 (name, value, nDays, path, domain, secure) {var today = new Date();var expires = new Date();
expires.setTime(today.getTime() + 3600000*24*nDays);
var curCookie = name + "=" + encodeURIComponent(value) + (expires ? "; expires=" + expires.toGMTString() : "") + (path ? "; path=" + path : "") + (domain ? "; domain=" + domain : "") + (secure ? "secure" : "");
document.cookie = curCookie;}</script>
</head>
<body><br>If you are not redirected to the shopping cart, click here</body></html>
and it works, but still does not work on my site. This code is being ran in an iframe from a different domain on my site. The site is www.shopthethirdfloor.com. If you go to products, select a product and add it to the cart, it does not add a cookie on safari, but does the other browsers.
ok, after a lot more digging and trial and error, it was the issue where safari would not set a cookie in an iframe cross domain. I tried several suggestions on the web including here, but they either were not relevant or did not work (were old). I found that I had 2 options. The first, change the framed domain to be a sub domain of the parent window domain which I could have done, but would have needed to change umpteen links and the payment gateway which I did not want to do. The second, took several steps, but works excellent is as follows:
The page that is trying to set the cookie checks if it is a safari browser and if it is, changes the window location to a php script on from the same domain as the browser passing the cookie in a get variable, this in turn changes the window location to an asp script from the iframe server sending it the cookie informtion which has the cookie setting code and after setting the cookie, loads the page for the the shopping cart.
The key here is getting the cookie setting page that needs to set the cookie into the parent window and then load the new destination page.
This has a few steps, but works well.
try to use HTML5 local storage concept to achieve cookie storage in safari browser
Default safari settings will be Cookies enable for trusted sites ,so you must enable the settings to enable cookie storage... TO overcome this issue you can use HTML5 local storage concept

chrome.storage.sync doesn't sync between machines

I have a simple extensions that saves some data to chrome storage
var dt = new Date();
var item = {};
item[$('#qteSymb').text() + "-" + guid()] = $('#newnote').val() + "-:-" + $.datepicker.formatDate('mm/dd/yy', dt) + " " + dt.getHours() + ":" + (dt.getMinutes() < 10 ? "0" + dt.getMinutes() : dt.getMinutes());
chrome.storage.sync.set(item, function(){
renderNotes();
});
This works fine locally - my extension is working as intended - but it doesn't sync back to another computer. I am assuming the sync is ON on both computers because the bookmarks, extensions, etc. sync just fine.
Thank you!
So I finally figured this out.
When not using Chrome Web Store your manifest file should include a key (https://developer.chrome.com/extensions/manifest.html#key)
...
"key":"myawesomeextension"
...
Without this every time you install the extension on a different device (through chrome://extensions/ --> Load unpacked extension) it gets a new id and therefore the data being synced doesn't get matched to the correct extension - same extension with different ids = two different extensions in the eyes of Chrome.
There is no need for a key once the extension is in Chrome Web Store. Hope this helps somebody keep some hair at some point.

Categories

Resources