How to do redirection with cookie - javascript

I want two types of domain redirects on the same site (if else statement etc):
If user has cookie:
And url subdomain is amazon then redirect to url xxxxxx
And url subdomain is ebay then redirect to url xxxx
If user has no cookie:
And url subdomain amazon then first forward to ebay subdomain and back to amazon subdomain once (currently creates a loop) and display background xxxx with href link xxxx
And url subdomain ebay then first forward to amazon subdomain and back to ebay subdomain once (currently creates a loop) and display background xxxx with href link xxxx
Synchronise user cross-domain click for a new pop-up for href xxxxx - ie if user has come on site by clicking on link on another site then see asynchronise click to open another pop-up (200 sec rule)
Currently site already has below which I still need, so cookie redirect shouldn't set a redirect to site outside because of the code below but only if user is genuinely a returning user
var subdomain = window.location.hostname.split('.')[0];
if (!document.cookie == null && subdomain === "amazon") {
window.location = "http://www..com";
} else if (!document.cookie == null && subdomain === "ebay") {
window.location = "http://www.tutorialspoint.com";
} else if (document.cookie == null && subdomain === "amazon") {
var oLinksArray = [];
oLinksArray[0] = 'http://www.ebay.com';
oLinksArray[1] = 'http://www.amazon.com';
for (var x = 0; x < 2; x++) {
var openWindow = window.open(oLinksArray[x]);
setTimeout(function() {
openWindow.close();
}, 2000);
}
} else if (document.cookie == null && subdomain === "ebay") {
var oLinksArray = [];
oLinksArray[0] = 'http://www.amazon.com';
oLinksArray[1] = 'http://www.ebay.com';
for (var x = 0; x < 2; x++) {
var openWindow = window.open(oLinksArray[x]);
setTimeout(function() {
openWindow.close();
}, 2000);
}
} else {}

You don't need to transfer cookie with redirection. Cookie has a property called domain. You should add website's domains to give access permission to them.
In Javascript
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=firstDomain.com,nextDomain.com;path=/";
In PHP
setcookie('mycookie','mydata1',time() + 2*7*24*60*60,'/','www.firstDomain.com,nextDomain.com', false);

Related

JS - Cookie management

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.

Script redirect by referrer url

Is it possible to write redirect script by using referrer url and get div element? Something like below:
Referrer is - sitename.com/example/#bang1#bang2#bang3
Redirect site - a href="http://anothersite.com/"id="redirectthis">Redirect this
Tried -
<script>
var separator1 = (document.referrer.indexOf('[tag]') !== 1)
var separator2 = (document.referrer.indexOf('[tag]') !== 2)
var separator3 = (document.referrer.indexOf('[tag]') !== 3)
var relocate = document.write(document.getElementById("redirectthis") + separator1 + separator3 + separator2);
window.location = relocate
</script>
Result wanted - This would lead a redirect to http://anothersite.com/bang1/bang3/bang2

Change Https to Http in a link for all subdomain using javascript or php

i need a script (JavaScript or PHP not mod_rewrite) which can replace all HTTPS to HTTP on all *subdomain.example.com link but keep HTTPS for example.com and www.example.com.
Eg: i want to turn
My sub domain
to
My sub domain
*There will be lot of different sub-domain...
Solution that doesn't require jQuery:
var as = document.getElementsByTagName('a') //get all a tags
var re = /^https:\/\/[\w\W]*(example.com)/i //http://*example.com
var reExcept = /^https:\/\/(www.)?(example.com)/i //filter https://www.example.com and http://example.com
for (var i=0; i<as.length; i++) {
href = as[i].getAttribute('href')
console.log('original href: ' + href)
if (!href || !re.test(href) || reExcept.test(href) )
continue //this href shouldn't be replaced
href = href.replace('https://', 'http://')
as[i].setAttribute('href', href)
console.log('replaced href: ' + as[i].getAttribute('href'))
}
Tested through console at https://www.google.com/search?q=google (with google.com instead of example.com in re and reExept). Seems to work fine.
A bit less wordy version:
var re = /^https:\/\/[\w\W]*(example.com)/i
var reExcept = /^https:\/\/(www.)?(example.com)/i
var as = document.getElementsByTagName('a')
for (var i=0; i<as.length; i++) {
href = as[i].getAttribute('href')
if ( !href || !re.test(href) || reExcept.test(href) )
continue
as[i].setAttribute('href', href.replace(/^https:\/\//i, 'http://'))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<a href="https://www.test.com" >Test 1 </a><br>
<a href="https://ftp.test.com" >Test 2 </a><br>
<a href="https://test.test.com" >Test 3 </a><br>
<script type="text/javascript">
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
}
else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
domain = domain.replace("www.", "");
return domain;
}
$("a").each(function(){
var url = $(this).attr("href");
var res = extractDomain( url );
var resSplit = res.split('.');
if( resSplit.length > 2 ){
$(this).attr("href", url.replace("https","http") );
}
});
</script>
Here's a solution in PHP. It also covers sub-sub domains like subsub.sub.example.com and domain names only like example.com.
Be aware that when you want to do it on the server side…
The script does a redirect (there are no alternatives) to change the protocol from https to http.
An encrypted connection with SSL / HTTPS is established before a (php) script can get control.
So, you can not use a server-side solution for cases where (e.g.) a certificate does not match some subdomain names, while others are matched.
<?php
$tochange = array(
'sub', 'sub1', 'test',
);
$hname = getenv("SERVER_NAME");
if (preg_match('/^(.*)(\.(.*?)\.(.*))$/s', $hname, $regs)) {
// $regs[1] contains subdomain name / names (also: *subsub.sub.domain.tld").
$encrypted = ((isset($_SERVER["HTTPS"])) && (strtoupper($_SERVER["HTTPS"]) == 'ON'));
if ($encrypted && (in_array($regs[1],$tochange))) {
$port = getenv("SERVER_PORT");
$query = ($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';
$url = 'httpx://' . $hname . $_SERVER['SCRIPT_NAME'] . $query;
// Do a redirect
header("location: $url"); // redirect
// echo "$url<br >"; // for testing
}
}
?>

Redirect a user to a URL from input, store in cookie

I'm working on a project in which the user is sent to the directory name they entered in an input, like so:
function sendanswer(e) {
if (e.keyCode === 13) {
e.preventDefault();
var answer = document.answerarea.input.value;
if (answer) {window.location.href = answer;}
}
}
document.answerarea.input.onkeypress = sendanswer;
This works fine. But now I want for the user to be automatically redirected to the directory they specified every time they visit the page, BUT only if they didn't recieve a 404 error after navigating to the directory. I imagine this would be accomplished by erasing the cookie when the 404 page is visited.
But how would the redirecting-to-cookie process work?
When you get input from use set a cookie using this code:
function sendanswer(e) {
if (e.keyCode === 13) {
e.preventDefault();
var answer = document.answerarea.input.value;
if (answer) {
window.location.href = answer;
//SET COOKIE WITH NAME redirectPath
document.cookie="redirectPath="+ answer;
}
}
}
Now on your home page (the page which user gets on visiting your site) add following call on-page load:
window.onload=function(){
var kuki = "redirectPath=";//NAME OF COOKIE WE SET
var cookies = document.cookie.split(';');
for(var i=0;i < cookies.length;i++) {
var c = cookies[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(kuki) == 0){
var path = c.substring(kuki.length,c.length);
//MOVE USER TO STORED PATH
document.location.href=path;
}
}
}
A better approach will be to read cookie on server-side and redirect user to their favourite folder from there.
For more reference check this answer.

Javascript validate email address with website domain name in ASP.NET C#

I've two text box in form
Example:
website address : http://www.domainname.com
email address : example.domainname.in
I want to validate email address domain name is same as web site domain name in javascript
I Have write a below code to validate domain name
var websiteaddress = $('#' + $("[id$=_websiteAdd]")[0].id).val();
var emailaddress = $('#' + $("[id$=_emailaddress]")[0].id).val();
if (websiteaddress != "" && emailaddress != "") {
var emailDomain = emailaddress.replace(/.*#/, "");
var websiteDomain = websiteaddress .replace('http://', '').replace('https://', '').replace('www.', '').split(/[/?#]/)[0];
if (emailDomain != websiteDomain) {
return false;
}
}
return true;
So you can do:
var email = 'something#domainname.com';
var domain = email.replace(/.*#/, "");
You can then compare the domain to the domain of the site.
You can do this using the code over at: http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain - this is useful if you don't know where the website will be hosted or if the domain changes depending on location. If the website domain won't change then you could just hard code websiteDomain.
var websiteDomain = (function(){
var i=0,domain=document.domain,p=domain.split('.'),s='_gd'+(new Date()).getTime();
while(i<(p.length-1) && document.cookie.indexOf(s+'='+s)==-1){
domain = p.slice(-1-(++i)).join('.');
document.cookie = s+"="+s+";domain="+domain+";";
}
document.cookie = s+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain="+domain+";";
return domain;
})();
So you could then do a check to see if:
domain == websiteDomain

Categories

Resources