Share cookies with other domains - javascript

I know that it's possible to allow other domains to read our domain cookie as long as they're sub domains of the same parent domain.
For example, intranet.abc.com and extranet.abc.com can allow cookies to be read by each other by specifying the domain property to .abc.com
Now, I'm really in need that I can allow other domains to read my domain cookie (they are not sub domains of the same domain). I have searched a lot of discussions on the internet => all say "NO" due to security issues. I'm not sure if I missed a solution out there because I don't see any security issues in this case. My server clearly ALLOWS this cookie to be read by an XYZ.COM domain because the cookie does not contain any sensitive information and XYZ.COM domain is my trusted domain,
In my opinion, there should be a way to specify a list of other domains that are allowed to read a particular cookie in our domain, just like CORS, the server can decide if the information should be available to some trusted domains.
Please tell me if it's possible without using a workaround and if so, how to do it?
If it's not possible, I really would like to know why.
Some information about what I'm implementing:
I'm implementing a file download and on client side I need to detect whether the download is complete by periodically checking for a download token in the cookie using an interval in javascript.
The logic of the current system I'm working on at the moment may store the files in 2 different servers. If the file is missing in the current server, it will download file in another server (another domain)
Thank you very much.

You can read off-domain cookies by opening an iframe to specially instrumented page on the other domain and using the window.postMessage API to communicate between windows. HTML5 only, obviously.
Simplifying the postMessage API somewhat for brevity, consult MDN developer pages for full details.
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
<iframe id="ifrm" src="http://other.domain.com/getCookie.html"></iframe>
<script>
var iframe = document.getElementById('ifrm');
window.addEventListener('message', function (e) {
if (e.source === iframe.contentWindow && e.origin === 'other.domain.com') {
var cookie = e.data;
//do something with cookie
}
});
//wait for the iframe to load...maybe ping it first...then
iframe.contentWindow.postMessage('give me the cookie:cookie name', 'other.domain.com');
</script>
/* in getCookie.html */
<script>
window.addEventListener('message', function (e) {
if (e.origin === 'your.domain.com') {
var soughtCookie = /give me the cookie\:(.*)/.exec(e.data)[1];
// read the cookie
var cookie = getCookieFn(soughtCookie)
e.source.postMessage(cookie.toString(), 'your.domain.com');
}
}, false);
</script>

you could have a backend web service which shares the contents of the cookie with the 3rd party, but then your server would have to hold the cookie value in session and have a session id that is some how shared with the other website.
Can also special page and redirection so that the cookie value is read and passed to your domain as a form submit.
Lets say your domain is yours.com and on page yours.com/page1 you set some cookie value.
Now xyz.com , another domain wants that value. xyz.com/somePage, redirects to yours.com/spl (along with parameter of the page to send user to say xyz.com/somePage2), Now yours.com/spl gets the cookie via JavaScript and then redirects to xyz.com/somePage2 passing the cookie value as a POST or a GET parameter.
Full working sample at http://sel2in.com/pages/prog/html/acrossSites/make.php (with a simple web service)
AJAX not example wont work but can do it with iframes.
Code :
coki.js (goes on the first site that wants to expose cookies)
function setCookie(cname,cvalue, daysExpire)
{
var d = new Date();
d.setTime(d.getTime()+(daysExpire * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires + " ; path=/ ;"
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
wsa.php (goes on site 1). To make it more secure can check the calling page/ container URL and use a dynamic secret key.
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
error_reporting(E_WARNING);
$d = $_REQUEST['s'];
if($d != "secret565"){
echo "Bad secret bye";
return;
}
$n = $_REQUEST['n'];
if($n == ""){
echo "No cookie name, bye";
return;
}
?>
<script src=coki.js>
</script>
<script >
n = '<?php echo "$n"?>'
v = getCookie(n)
//alert("For " + n + ", got :" + v + ".")
window.parent.gotVal(n, v)
</script>
getc.html
Goes on site 2, gets the value of cookie C1 or other cookie from site 1 via wsa.php, using an iframe. wsa.php reads the secret auth key and cookie name from its parameters, then calls a javascript function in containing page to pass back values
<form name=f1 action=ws.php method=post>
<h1>Get cookie from Javascript sample </h1>
http://sel2in.com/pages/prog/html/acrossSites/
<table>
<tr><td>Url from <td/><td> <input name=u1 value='wsa.php' size=100><td/></tr>
<tr><td>Cookie Name <td/><td> <input name=n value='C1'><td/></tr>
<tr><td>Secret <td/><td> <input name=s value='secret565'><td/></tr>
<tr><td><input type=button value='Go' onclick='s1do()' > <td/><td><td/></tr>
</table>
</form>
<div id = result>result here</div>
<div id = cc1>container</div>
v 2 c
<script>
function gotVal(n, v){
document.getElementById("result").innerHTML = "For " + n + ", got :" + v + "."
}
function s1do(){
document.getElementById("cc1").innerHTML = ""
n1 = document.f1.n.value
s1 = document.f1.s.value
url = document.f1.u1.value
qry = "s=" + escape(s1) + "&n=" + escape(n1)
s = "<iframe border=0 height =1 width=1 src=\"" + url + "?" + qry + "\" ></iframe>"
document.getElementById("cc1").innerHTML = s
}
</script>

Related

How can I stop a background video playing every time the user returns to the home page?

I have been handed a design which requires a background video to load when the users hits the home page. I realise that this isn't best practice, but the design has been signed off by the client, so trying to develop a decent solution for it. I have video in place and it is working nicely.
I have also been asked to ensure that the video only loads once when the user visits the site and when they navigate about the site, if they return to home, the video shouldn't play again.
I have been searching about the web, but can't find a precedent for this. Could anyone suggest a possible solution for this to work? Or some documentation that I could visit to source one?
The site is written with HTML, CSS and JQuery.
I appreciate that there isn't any code to see, but any suggestions would be much appreciated.
Thank you to anyone who stumbles across this.
Use localStorage or sessionStorage:
Supposing you have a video element with an id, e.g.:
<video id="myVideo">...</video>
Your script might look something like this:
if (!localStorage.getItem('alreadyPlayedVideo')) {
const myVideo = document.getElementById('myVideo');
myVideo.play();
localStorage.setItem('alreadyPlayedVideo', true);
}
It would look the same with sessionStorage. The primary difference between the two is that sessionStorage is cleared when the user exits the browser or closes the tab, whereas localStorage persists between sessions.
You have to check if the user was already on the site, so you have to save this data somewhere, data can be saved in session, database, localStorage or in cookies.
Using cookies would be the best option for this scenario. Cookies gets stored on client side and can be used for session and state management
Cookie usage with JS
function setCookie(cookieName, cookieValue, expireDays,isGlobal) {
var expireDate = new Date();
expireDate.setTime(d.getTime() + (expireDays*24*60*60*1000));
var expires = "expires="+expireDate.toUTCString();
if(isGlobal){
document.cookie = cookieName + "=" + cookieValue + "; " + expires+"; path=/";
}else{
document.cookie = cookieName + "=" + cookieValue + "; " + expires;
}
}
function getCookie(cookieName) {
var name = cookieName + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie(cookieName) {
if (getCookie(cookieName) != "") {
return true;
} else {
return false;
}
}
$(document).ready(function(){
if(checkCookie('visited')){
//Stop playing video
}else{
setCookie('visited',1,3,false);
//Play video automatically
}
});

Run a function if a cookie exists

Okay, I'm new to javascript coding, cookies etc., and I can't quite find the answer to my problem on the net. I'm trying to create a site that has a div that displays some helpful information at the top.
<div id="helpdiv">
<!--This content shows only on web browsers Internet Explorer 6/7/8/9/10/11 and Microsoft Edge.-->
Looks like your using Internet Explorer/Edge. This site is optimized when "Compatibility Mode" is disabled. Thank you!
</div>
I found some code that I can use that will show this div for 8 seconds, then disappear. But I want this to only show up once.
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I figured if a cookie was used, then the browser could check for that cookie, and if it existed, then it wouldn't need to show the div. Only the first time they visited the site.
So here's the flow I'm trying to acheive:
Check for a cookie named “helpText”
If the cookie doesn’t exist:
I want to run a function that hides a div (id="helpdiv") after 8 seconds of showing.
Here is some code I found that hides a div:
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I then want to set a site cookie called ”helpText” so that next time they visit the site, the function won’t run again.
If cookie exists:
I want the div with an Id of “helpdiv” to have the style=“display:none;”
If I need to add anymore code, please let me know and I can explain more. Any help would be a life saver!!
You can check for cookies on the current web document like this:
document.cookie
So if you are planning to check for a specific string you could do an indexOf("") with the word you are looking for and validating if the index is more than 0.
if(document.cookie.indexOf("helpText") > 0 ){
the cookie was found, so your function should be here
}else{
cookie not found
}
Probably is better to do a search over Stackoverflow because there are a lot of answers about cookies and javascript:
Here It's a full answer about this:
Check if cookie exists else set cookie to Expire in 10 days
Extending on Lemmy's answer, this is what you need:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
Here is the updated script for your wordpress environment:
<script type="text/javascript">
jQuery(document).ready(function($){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
//setTimeout(closeHelpDiv, 2000);
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
In Wordpress you must use change the $ sign with jQuery and pass the $ sign into the function. The dollar sign in $(document).ready(function(){}); is not used for compatibility with other libraries.
try
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
from
Get cookie by name
Use it to check whether the cookie exists or not.
In your code you can easily
if(getCookie('helpText')!=''){
$('selector').css('attrib','prop');
}
So you need to set a cookie after displaying banner to user on her first visit -
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
document.cookie="visitedBefore=true; expires=1 Jan 9999 12:00:00 UTC; path=/";
}
check with following code if that user already visited your site
function showBanner(){
// check if visited Earlier
if(!getCookie('visitedBefore'))){
window.setTimeout( closeHelpDiv, 8000 );
}
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
showBanner();
So you are doing all things correct just use cookies as described above.

Third party cookie to check if the browser block it by default

I want to check which browser blocks by default third party cookie.
I though to create a local file .html with a third party cookie and open it to every browser to check it will open. Is this a good option?
I plan to use this example but is it a third party cookie?
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
This code will create a 1st party cookie - i.e. the domain of this cookie will match the domain of the page loaded.
In order to create a third party cookie you must request a resource from a different domain than the page that requests that resource. This resource could set a cookie using either javascript or HTTP header command (which is initiated by server side code like PHP).
If you are just doing your own survey to gain information about which browsers accept 3rd party cookies by default then it may be worthwhile looking at the specification for each browser to see what the official line is before going to the effort of testing.

set client cookie to prevent re-registration

I don't have access to run server-side code, so I can't do a PHP session for a registration form. I am going with a client cookie to ensure only one registration per person (per unique e-mail).
Following How do I set/unset cookie with jQuery? I thought I got the hang of it.
But it seems, even if I put in a new e-mail, it will always return alert("You've already registered");. Why is that?
$("#submitBtn").click(function (event) {
var subject = "Registration for Walk-a-thon",
name = document.getElementById("name").value,
email = document.getElementById("email").value,
message = document.getElementById("message").value;
if (!$.cookie('client_email_cookie')) {
$.cookie("client_email_cookie", email, { path: '/', expires : 10});
log("Cookie: " + $.cookie("client_email_cookie"));
var link = "mailto:Jun.Ma2#otis.com; Allison.Rocca#utc.com"
+ "?cc=daniel.turcotte#carrier.utc.com"
+ "&subject=" + escape(subject)
+ "&body=" + escape(message)
;
window.location.href = link;
}
else {
alert("You've already registered");
}
});
if (!$.cookie('client_email_cookie')) only checks to see if the cookie exists, it doesn't check its value.
$.cookie('client_email_cookie') returns the value of the cookie (in your case email). Compare that value to the email that was entered to see if it has been registered.
Also, not to state the obvious, but this can be easily defeated anyway by the user simply deleting the cookie if they so desire, registering from a different browser or computer, using private browsing, etc...

Tracking values using JavaScript

on page A
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString());
on page B
_gaq.push(['pageTrackerTime._trackEvent', 'category', 'action', document.location.href, roundleaveSiteEnd]);
when a user clicks a button on page A , he will be directed to page B and there I used document.location.href to track the current URL. now I would like to track as well session_name from page A using JavaScript.
how can I do this
the original code was like this
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM Tmyapp_Session;";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
test.Controls.Add(GetLabel(thisReader["session_id"].ToString(), thisReader["session_name"].ToString()));
string[] compare = secondResult.Split(';');
foreach (string word in compare)
{
if (word == thisReader["session_id"].ToString())
{
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
I had to change the last code to
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
session_id to session_name
because i want to url to have the value of the session_name
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
// include getCookie and setCookie functions here
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var username = getCookie("username");
if (username != null) { // registered user
document.writeln("Welcome back " +
username + ".");
var visits = getCookie("visits");
document.writeln(" You have been here " +
visits + " time(s) before.");
setCookie("visits",parseInt(visits)+1);
}
else { // new user
var username = prompt("What is your name ?","");
if (username != null) {
setCookie("username",username);
setCookie("visits",1);
document.writeln("Thank you. Please reload this page.");
}
}
</SCRIPT>
</BODY>
</HTML>
Hope this will work !!!
Looks like you just need to get the session_name from the querystring. Check out this post here, it has a couple of nice solutions for doing that.
I see two ways of accomplishing what you want, you could add another querystring
/url.aspx?session_name=[session_name]&session_id=[session_id]
or in a session variable
session["session_id"] = session_id;

Categories

Resources