So I am building an app for a client in jQuery, this is placed in an IFrame on their website. This app reads data from a JSON that is generated by their CMS and then sets page layouts etc from a query string.
The client me to set a cookie of the last visited page when linked off to an external page. Then on coming back to the app it will check if a cookie has been set, if so then redirect to that last visited page.
I am using https://github.com/carhartl/jquery-cookie plugin for easier cookie integration.
My code so far:
//Get current URL
var complete_url = document.URL;
//Define last location cookie
var last_location = $.cookie('last_location');
//On page read set last_location as current location
$(document).ready(function() {
$.cookie('last_location', complete_url, {
expires: 0,
path: '/'
});
});
//if page_location is set navigate to that location
if (last_location && last_location != complete_url) {
window.location = last_location;
}
This obviously doesn't work as you'd get stuck in an infinite loop and I am struggling to get this right as it is my first day back at work from Christmas, ha.
If you are able to help that would be great!
Also I'm sorry if this is unclear I can try and reword it if need be.
Thanks.
[NOT SOLVED]
var pattern = new RegExp(window.location.host);
$('a').click(function() {
var href = $(this).attr('href');
if(pattern.test(href) !== true) {
$.cookie('last_location', document.URL, {
expires: 7,
path: '/'
});
}
});
var referrer = window.parent.document.referrer,
current = document.domain;
if(referrer.indexOf(current) === -1) {
var last_location = $.cookie('last_location'),
current_location = document.URL;
if(typeof last_location !== 'undefined' && last_location !== current_location) {
$.removeCookie('last_location');
window.location = last_location;
}
}
[NEW SOLUTION]
I have come up with a new solution that doesn't depend on the document.referrer
var last_location = $.cookie('last_location'),
current_location = document.URL;
//Initial check if cookie is set and not equal to current location
if (last_location && last_location !== current_location) {
window.location = last_location;
}
//Set pattern
var pattern = new RegExp(window.location.host);
//On any link click test if the href does not have a match with the pattern
$('a').click(function() {
var href = $(this).attr('href');
if (pattern.test(href) !== true) {
//If no match found, the link is external and adding current url to the cookies
$.cookie('last_location', document.URL, {
expires: 1,
path: '/'
});
} else {
//Else if link is internal remove cookie and continue as normal
$.removeCookie('last_location', {
path: '/'
});
}
});