Loop on back button after re-direction with querystring - javascript

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.

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.

Javascript redirect concatenates url linstead of redirecting

I want to call a controller action whenever a value is updated from a textbox.
Note that this script sits inside the same view which will be returned from the Dispatch/Index controller action
I tried doing it like this:
<script>
$('#deliveryDate').change(function () {
var date = $('#deliveryDate').val();
var sDate = date.split('/');
location.href = 'dispatch/' + sDate[0] + sDate[1] + sDate[2];
});
</script>
And it works perfectly the first time the value changes (ie, the page redirects to /dispatch/12122016).
However, when I change the value again, it redirects to /dispatch/dispatch/13122016, so the value just keeps concatanating and this of course produces an error.
I tried chaging the redirect line to location.href = '#Url.Action("Index", "Dispatch")/' + sDate[0] + sDate[1] + sDate[2];, but now it just concatenates the new date on to the url instead of redirecting how I need it to... (ie, it navigates to /dispatch/12122016/13122016)
Is there ANY way of doing this without including the literal url path??
How can "clear" the current url before redirecting the action I need (which should just be dispatch/12122016 ?
Simply prepend a forward slash in the URL, this should always dictate that the url change is always bound to be absolute.
As a bonus: I also changed your date concatenation after /dispatch into a join.
$('#deliveryDate').change(function () {
var date = $('#deliveryDate').val();
location.href = '/dispatch/' + date.split('/').join('');
});
Try this by appending the forward slash. Because your concatenating the dispatch string on every redirect
<script>
$('#deliveryDate').change(function () {
var date = $('#deliveryDate').val();
var sDate = date.split('/');
Var URL = '/dispatch/' + sDate[0] + sDate[1] + sDate[2];
Window.location.href = URL
});
</script>

Javascript window.location redirect with url rewriting, no querystring

I have endlessly googled for about an hour, so please forgive me if this has been asked before.
I am using pure Javascript and do not wish to use jQuery.
PREAMBLE
I have an HTML form with 3 select boxes that control a search of items. When one is updated, a simple function reads each of the values in the select boxes and produces a URL that matches our URL rewriting standard.
http://www.example.com/search/select1/data1/select2/data2/select3/data3/
This is then used in a
history.pushState
to update the browser's url address so a user can bookmark the page right away. This works fine.
PROBLEM
When the user presses the button of the form, what I want is the function to read all the select box values, generate the URL as before but also load this specific URL so that the underlying database code can return the results for that search on the page.
However, when I use
window.location.href
it loads the page, but also sends the querystring from the form submission. This mucks up the database code because, essentially, it's getting all the data twice.
EXAMPLE
I choose 'A' from select1, 'D' from select2 and 'E' from select3.
This results:
http://www.example.com/search/select1/A/select2/D/select3/E/?select1=A&select2=D&select3=E
SO...
Is it possible to generate the URL in the correct rewritten format, then load the page without the querystring?
JAVASCRIPT
function changepage(loadpage)
{
var theform
theform = document.getElementById("searchform");
var pageurl
pageurl = 'http://www.example.com/search/'
var select1 = theform.select1.value;
var select2 = theform.select2.value;
var select3 = theform.select3.value;
if(select1 != '')
{
pageurl = pageurl + 'select1/' + select1 + '/';
}
if(select2 != '')
{
pageurl = pageurl + 'select2/' + select2 + '/';
}
if(select3 != '')
{
pageurl = pageurl + 'select3/' + select3 + '/';
}
history.pushState('data', '', pageurl);
if(loadpage=='yes')
{
window.location.href = pageurl;
}
}
HTML
<form method="post" action="form.asp">
<select id="select1"><option>A</option><option>B</option></select>
<select id="select2"><option>C</option><option>D</option></select>
<select id="select3"><option>E</option><option>F</option></select>
<button onClick="changepage('yes');">
</form>

Append parameter in url without reloading page

I am using following code to append param to url. This is working fine but when parameter is appended in url, page is getting reloaded. I want to use this functionality without reloading the page .
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
alert('sdfadsf');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
//alert(document.location.href);
}
I want to add multiple params to url without reloading the page like:
txt1
txt2
txt3
link1
link2
link3
i want url : "..../search.php"
after click on txt2
i want url : "..../search.php#t_2"
after click on link2
i want url : "..../search.php#t_1&l_2"
You can only do this using history.pushState(state, title, url) which is an HTML5 feature.
There is a new feature that aims to replace the use of location.hash with a better solution: pushState.
window.history.pushState(data, "Title", "/new-url");
More information: http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate

Window.Open causing issue when URL doesnot contain http

I have a textbox where the user can enter URL and button named Check link. On clicking button, a new window should be opened with the URL entered by the user. If i enter URL as "http://google.com" then window.open('http://google.com'); is working fine but if i enter "www.google.com" then it is appending to the current window url (http://localhost:1234www.google.com) which is not a valid url. How to make this work?
Thanks in advance
Check & prepend
if (!/^(http:|https:)/i.test(url))
url = "http://" + url;
try this:
function f(url) {
if (url.indexOf("http://") == -1) {
url = "http://" + url;
}
window.open(url);
}
If your question is "How do I test if a string starts with 'http://' and if not prepend it?" then something like this:
var url = "somestring.com"; // as set from your textbox
if (0 != url.toLowerCase().indexOf("http"))
url = "http://" + url;
It would be wise to trim leading and trailing spaces before doing this test, but I'll leave that as an exercise for the reader...
Add a onclick button function and handle the text in that.
function checkLink() {
var url = document.getElementById("textbox-id").value;
if(url.substr(0,7) != "http://") {
alert("Invalid URL! Please make it like http://myurl.com");
return false;
}
}

Categories

Resources