This is code which shows URL and delete image for delete cookie. add and display function is working but how to delete ??
function backLinks(){
var pathname = window.location;
var patientName = document.getElementById("general:patientDetailName").value;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
// for writing Cookie
var stringCookie = "<span class='backLinkText1'><img src='../images/deleteImg.png' alt='' class='backLinkDeleteButton' onClick='deleteBackLink()'/></span><a class='backLinkText' href=\""+pathname+"\"> Patient History For \""+patientName+"\"</a>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
**
function deleteBackLink(val){
jQuery.cookie(val, null);
}
**
How can I create a delete function and what parameter will I pass to it?
got a correct answer ...
in this i will replace cookie and delete inner html
function backLinks(stringValueAndName, patientName, patientDOB){
var pathname = window.location;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
var time = new Date();
var spanId = time.getTime();
// for wright in Cookie
var stringCookie = "<span id ="+spanId+"> <img src='../images/deleteImg.png' class='backLinkDeleteButton' onClick='deleteBackLink("+spanId+")'/><a class='backLinkText' href=\""+pathname+"\">"+stringValueAndName +patientName+' ('+patientDOB +')'+"\</a></span>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
function deleteBackLink(val){
jQuery('#'+val).remove();
var stringCookie = jQuery('#backButtonSpan div').html();
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
}
To delete a cookie with jQuery, set the value to null:
jQuery.cookie("name", null);
So your function will work - just pass the cookie name as a parameter:
deleteBackLink("name");
It doesn't. A cookie is a cookie.
The closest it comes is the HTTP Only flag, which allows a cookie to be hidden from JavaScript(mean client side). (This provides a little defence against XSS cookie theft).
A cookie is a cookie. (Again, client side code can't touch an HTTP only cookie)
Related
I made this little code using JS to disable cookies:
$(document).ready(function() {
var cookie_settings = getCookie("cookie-settings"); //Main cookie which contains cookie preferences
var cookie_selector = document.getElementById("cookie-selector"); //Modal for cookie selection
var g_recaptcha = document.getElementById("cookie-g-recaptcha"); //Example checkbox cookie
var g_tag_manager = document.getElementById("cookie-g-tag-manager"); //Example checkbox cookie
var messenger_plugin = document.getElementById("cookie-fb-mccp"); //Example checkbox cookie
var g_analytics = document.getElementById("cookie-g-analytics"); //Example checkbox cookie
var cookie_set = document.getElementById("cookie-set"); //Button to save preferences
if (cookie_settings == null) { //Check if main cookie exist
$(cookie_selector).modal({
backdrop: 'static',
keyboard: false
}); //If not exist, open cookie selector modal
} else {
var cookie_settings_raw_values = getCookie("cookie-settings"); //read and save main cookie in var
var cookie_settings_values = cookie_settings_raw_values.split('&'); //save main cookie content in array
if (cookie_settings_values.includes(g_recaptcha.id)) {
//If array contains recaptcha example include it
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(g_tag_manager.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(messenger_plugin.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
if (cookie_settings_values.includes(g_analytics.id)) {
//same
//for example append in head -> $('head').append('myscript');
}
//or you can remove else condition and manage this part from php
}
$(cookie_set).click(function() { //on save preferences click
var selected_cookies = [g_recaptcha.id, g_tag_manager.id]; //make array and include required cookies
if (messenger_plugin.checked == true) {
//if messenger plugin example checkbox is checked push it's reference in array
selected_cookies.push(messenger_plugin.id);
}
if (g_analytics.checked == true) {
//same for the other optional checkboxes
selected_cookies.push(g_analytics.id);
}
var expiry_date = new Date();
expiry_date.setMonth(expiry_date.getMonth() + 6); //expiration date 6 months in my case, you can set what you want
document.cookie = document.cookie = "cookie-settings=" + selected_cookies.join('&') + "; expires=" + expiry_date.toGMTString(); //make main cookie with required and optional selected checkboxes (the deadline is 6 months after the creation of the cookie)
location.reload(); //reload page
});
//get cookie by name
function getCookie(name) {
var document_cookie = document.cookie;
var prefix = name + "=";
var begin = document_cookie.indexOf("; " + prefix);
if (begin == -1) {
begin = document_cookie.indexOf(prefix);
if (begin != 0) {
return null;
}
} else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = document_cookie.length;
}
}
return decodeURI(document_cookie.substring(begin + prefix.length, end));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My question is it enough to disable third-party cookies?
Not including the scripts if the user does not accept cookies, do the stored ones become useless? Does the site comply with the GDPR?
If not, do you have any other valid alternative to propose that is not the use of third party codes?
Most of the websites, which are trying to be GDPR compliant are not loading any of these scripts by default (as you probably do). First they show a popup, if a user wants to load e.g. tracking cookies and if the user agrees they will be loaded. The configured setting which services should be loaded / what the user has selected will then be stored either in a cookie or e.g. the localStorage.
So yes, your site seems to be GDPR compliant when we take a look at the approach how you load the external scripts.
If you’re talking about deleting them, set it again with the expiry date before today.
I'm trying to change the URL in the address bar using javascript.
So if the user access the page using
www.example.com/ajax/project8.html
Url should be changed automatically to
www.examp.com/#cbp=ajax/project8.html
shouldn't be any harder than this:
window.location = "http://whatever.you.want.com"
UPDATE
So you want your site to redirect to another page when the url is www.example.com/ajax/project.aspx?id=whatever and id=xxx could be any id.
To achieve that you need a function that returns the query string parameter value eg:id=whatever
Then check if the current url needs to be redirected to another page. If this is the case then redirect to new url with same parameter value.
/*
function that returns a query string parameter value
this function works with many parameters
Eg: www.example.com/#cbp=ajax/project.aspx?myParam=hello&id=1283&otherParam=234
to get the param value just give it the parameters name
getQueryStringValue("id") returns : 1283
getQueryStringValue("myParam") returns : "hello"
*/
function getQueryStringValue( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
//current url
var currentUrl = location.href;
//check if current url contains www.example.com/ajax/project.aspx
if (currentUrl.indexOf("www.example.com/ajax/project.aspx") != -1 ){
//new url for redirection
var newUrl = "www.example.com/#cbp=ajax/project.aspx?id=" + getQueryStringValue( "id" );
//redirect to new page
location.href = newUrl;
}
Try this code
if (window.location.href == 'www.example.com/ajax/project8.html') {
window.location = 'www.examp.com/#cbp=ajax/project8.html';
}
you can set all things like
window.location.href = "www.examp.com/#cbp=ajax/project8.html"
for more details how you will manage all url parameter then please see
JavaScript and jQuery url managment
window.location.href = "#cbp=ajax/project8.html";
you can change the value written after # to any location , div id etc.
e.g
window.location.href = "#myDivID";
<meta http-equiv="refresh" content="0; url=http://example.com/" />
Note: please put on header
or
<script type="text/javascript">
window.location.assign("http://www.example.com")
</script>
The problem:
I need to start with a URL with a query string containing a URL of a second page - http://www.firstURL.com/?http://www.secondURL.com. On the target page of the first URL, the query string is parsed to extract the second URL and the browser is re-directed to the second URL. This is done on $(document).ready so that it's automatic. This all works fine, but of course falls in a hole if the user hits the back button on the second URL. Here's the basic code:
$(document).ready(function() {
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
location.href = '' + loc + '';
} else {
//do something else on the target page..
}
});
I've tried creating a conditional case where, if the referrer is the 2nd URL (loc in the code above), the re-direction doesn't execute, but it seems that in the case of a re-direction, the back button doesn't return the referrer.
I have to do all this client side - I have no access to the server.
Is there some way to prevent the re-direction triggering on a back button click? Thanks.
Once you hit the second page, set a cookie in your browser indicating that the second page has been visited.
In the first page, before doing the redirection always check whether the cookie is not present.
Instructions on setting a cookie:
<script type="text/javascript">
document.cookie="secondpagevisited=43yj0u3jt;path=/"; //execute this line in the head of second page.
</script>
In first page, check for cookie presence:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
/*do redirection here*/
}
</script>
EDIT: Assuming you control only the first page and not the second page, try this:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
document.cookie="secondpagevisited=43yj0u3jt;path=/";
/*do redirection here*/
}
</script>
I gave Ashish the point for putting me on the right track, but this is my solution which goes one step further:
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
if (document.cookie.indexOf('redirected=' + loc + '') == -1) {
document.cookie = 'redirected=' + loc + '';
location.href = '' + loc + '';
} else {
var url = location.href.replace('' + s + '', '');
document.cookie = 'redirected=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
history.pushState(null, null, '' + url + '');
}
If the cookie is there, the re-direction doesn't occur, the cookie is removed (in case the user returns to the site that had the original link and clicks it again), and the URL is tidied up by removing the query string.
Thanks for the guidance.
Just a day ago I posted this question and found/built my own solution, for lack of a sufficient answer. Now, I need help going through a similar process again. This time, however, I need to capture (save to cookie as 'Base64' data) and recall (recheck upon user return) the state of all the radio button groups (by 'name' not 'ID', for obvious reasons), after the page loads, and if need be trigger all corresponding onchange events attached to them. For example, if a radio button group label has the question, "Have you lived at this address for more than 3 years?' one radio button label says 'Yes', and the other, 'No'. If the user chooses 'No' an extra 'address' table row is displayed in the table. All of the mechanics of the table appearing on 'No' 'checked' has already been done. I'm looking for a simple way to:
A:) Record all radio button group(s) state(s) (i.e which one is checked), on the 'onchange' event of any radio button on the form.
B:) Convert that information to JSON or some other record keeping
C:) Base64 encode data in step [B:]
D:) Save to a cookie
Upon page reload (user returns to page)...
E:) Grab data from cookie
F:) Decode Base64 and assign to variable
G:) From data iterate through all the forms radio buttons re-checking what was originally checked.
Sound easy? Give it a try! I did....and am still.
Here's the basics in jQuery without the cookie saving, will leave that to you
var radioState={};
$(':radio').each(function(){
if(!radioState[this.name]){
radioState[this.name]={};
}
radioState[this.name][this.value]=this.checked
});
/* stringify to JSOn and convert to Base64 */
var storeString= btoa(JSON.stringify(radioState));
/* store in cookie*/
/* on page load pull data from cookie (if exists) - add a cookie validation test*/
var cookieString=storeString;// just using this for demo
var newPageState= JSON.parse(atob(cookieString));
/* loop through radios setting state */
$(':radio').prop('checked',function(){
return newPageState[this.name][this.value];
});
DEMO
atob() and btoa() docs
EDIT: Use localStorage if browser supported, with cookie fallback. Will minimize cookie size sent to server for each and every http request made to site
Thank You #Charlietfl. +1! Here is the complete 'save_form.js' code!
//<!-- Prerequisites: jquery.min.js -->
//<!-- A script to set a cookie [Argument(s) accepted: Cookie Name, Cookie Value, etc.] [BEGIN] -->
function set_cookie ( name, value, path, domain, secure )
{
var cookie_string = name + "=" + escape ( value );
var cookie_date = new Date(); // current date & time ;
var cookie_date_num = cookie_date.getTime(); // convert cookie_date to milliseconds ;
cookie_date_num += 35 * 60 * 1000; // add 35 minutes in milliseconds ;
cookie_date.setTime(cookie_date_num); // set my_date Date object 35 minutes forward ;
cookie_string += "; expires=" + cookie_date.toGMTString();
if ( path )
cookie_string += "; path=" + escape ( path );
if ( domain )
cookie_string += "; domain=" + escape ( domain );
if ( secure )
cookie_string += "; secure";
document.cookie = cookie_string;
};
//<!-- A script to set a cookie [Argument(s) accepted: Cookie Name, Cookie Value, etc.] [END] -->
//<!-- A script to grab a cookies value by name [Argument(s) accepted: Cookies Name] [BEGIN] -->
function get_cookie ( cookie_name )
{
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
if ( results )
{
return ( unescape ( results[2] ) );
}
else
{
return null;
};
};
//<!-- A script to grab a cookies value by name [Argument(s) accepted: Cookies Name] [END] -->
function populateCookieFromForm ( cookieName ) {
var encodedCookie;
var preCookieObj = '{';
var allMainElements = $('form').find('input[type=text], select');
for (var i=0; i < allMainElements.length; i++)
{
preCookieObj = preCookieObj + '"' + allMainElements[i].name +'":"'+ allMainElements[i].value +'",';
};
preCookieObj = preCookieObj.substring(0, preCookieObj.length - 1);
preCookieObj = preCookieObj + '}';
//<!-- btoa() encodes 'string' argument into Base64 encoding -->
encodedCookie = btoa( preCookieObj );
set_cookie(cookieName, encodedCookie);
};
function populateFormFromCookie (cookieName) {
if ( ! get_cookie ( cookieName ) )
{
//<!-- Do Nothing - No Cookie For this form set. -->
}
else
{
//<!-- atob() decodes 'string' argument from Base64 encoding -->
jSONCookieObj = atob( get_cookie ( cookieName ) ) ;
jSONObj = JSON.parse( jSONCookieObj );
var allMainElements = $('form').find('input[type=text], select');
for (var i=0; i < allMainElements.length; i++)
{
var elementName = allMainElements[i].name;
var elementValue = jSONObj[elementName];
allMainElements[i].value = elementValue;
};
};
};
function populateCookieFromRadios (cookieName) {
var radioState={};
$(':radio').each(function(){
if(!radioState[this.name]){
radioState[this.name]={};
}
radioState[this.name][this.value]=this.checked;
});
/* stringify to JSON and convert to Base64 */
var storeString= btoa(JSON.stringify(radioState));
/* store in cookie*/
set_cookie(cookieName, storeString);
};
function populateRadiosFromCookie (cookieName) {
if ( ! get_cookie ( cookieName ) )
{
//<!-- Do Nothing - No Cookie For this form set. -->
}
else
{
var cookieString = get_cookie ( cookieName );
var newPageState= JSON.parse(atob(cookieString));
/* loop through radios setting state */
$(':radio').prop('checked',function(){
return newPageState[this.name][this.value];
});
};
};
This is how you properly call these functions. Near the bottom of the HTML/PHP page containing the form, place this JavaScript respectively:
<script type="text/javascript">
//<!-- If returning user detected, populate form with cookie values [BEGIN] -->
populateFormFromCookie('thisForm');
populateRadiosFromCookie('thisFormRadios');
//<!-- If returning user detected, populate form with 'section' cookie values [END] -->
//<!-- On change of ALL form elements re-save form cookie(s) [BEGIN] -->
$('input[type=radio]', $('form')).on('change',function(e){
populateCookieFromRadios('thisFormRadios');
});
$('input[type=text], select, textarea', $('form')).on('change',function(e){
populateCookieFromForm('thisForm');
});
$('input[type=text]', $('form')).on('input',function(e){
populateCookieFromForm('thisForm');
});
//<!-- On change of ALL form elements re-save form cookie(s) [END] -->
</script>
The next task is to see if all of this can be done without jQuery...hmm...
I am using jquery-cookie library to create cookie with JQuery. How can I update value of the cookie? I need it create new cookie and if the cookie exists to update it. How can I do this?
Code that I got:
v.on('click', function(){
var d = $(this).attr('role');
if(d == 'yes')
{
glas = 'koristan.'
}else {
glas = 'nekoristan.'
};
text = 'Ovaj komentar vam je bio ' + glas;
//This part here create cookie
if(id_u == 0){
$.cookie('010', id + '-' + d);
}
$.post('<?php echo base_url() ?>rating/rat_counter', {id : id, vote : d, id_u : id_u}, function(){
c.fadeOut('fast').empty().append('<p>' + text).hide().fadeIn('fast');
});
})
To update a cookie all you need to do is create a cookie with the same name and a different value.
Edit
To append your new value to the old...
//Im not familiar with this library but
//I assume this syntax gets the cookie value.
var oldCookieValue = $.cookie('010');
//Create new cookie with same name and concatenate the old and new desired value.
$.cookie('010', oldCookieValue + "-" + id);
watch out for this link
http://www.electrictoolbox.com/jquery-cookies/
here you see all important thing you can do with cookies.
if you want to know if an cookie already exists, just use this
if($.cookie("example") != null)
{
//cookie already exists
}