I'm trying to create a multi-search engine that would also store the user's "favorite" websites, but I can't find a way to store the user's websites (I just want to save website href I'd get in the HTML code) in the cookies and be able to retrieve them when the page is loaded.
My goal is to store some websites that users would "add to his page" to be able to load them when the user loads the page with this code:
function add_shortcut() {
var url = prompt("Please enter a website URL (e.g. nytimes.com) : ");
if (url != null) {
websiteName = get_short_name(url);
document.getElementById("generated").innerHTML += `<figure><a class="single-shortcut" href="https://www.${url}">
<img src="https://www.${url}/favicon.ico" onerror="this.src='src/img/void.png'">
<br/><figcaption">${websiteName}</figcaption></a></figure>`
}
}
function get_short_name(string) {
string = string.substr(0, string.indexOf('.'))
string = string.charAt(0).toUpperCase() + string.slice(1)
if (string.length >= 8) {string = string.substr(0, 7) + "..."}
return string
}
The javascript code I use to store everything I keep in cookies:
myCookie = {}
function get_expiration_date() {
var date = new Date();
var year = date.getFullYear() + 1;
return "expires=" + new Date(year, date.getMonth(), 28) + ";";
}
function save_cookies() {
myCookie["sengine"] = detect_search_engine();
document.cookie = "";
var cookieString = "";
for (var key in myCookie) {
cookieString = key + "=" + myCookie[key] + ";" + get_expiration_date();
document.cookie = cookieString;
}
}
function load_cookies() {
myCookie = {};
var key_value = document.cookie.split(";");
for (var id in key_value) {
var cookie = key_value[id].split("=");
myCookie[cookie[0].trim()] = cookie[1];
}
select_last_search_engine(myCookie["sengine"].toLowerCase());
}
My problem is that I don't know how to get all the hrefs in a div, then put it in a string that I would store in cookies/localStorage to retrieve it and load it when the page loads...
The whole project on GitHub: https://github.com/Vianpyro/Viaable
Related
What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link or not so if not it would push that new link to the array and would again recreate the cookie with the new array which would contain the new pushed link so what I am facing right now is that everytime the if function which checks for the unique link always comes true I am not sure that what's the problem?
Can you people please have a look over it :
<script type="text/javascript">
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var url = window.location.href;
var pathname = new URL(url).pathname;
var jsonObj = [];
//jsonObj.push("test");
var x = readCookie('vid_cookies');
if (x) {
var res = x.split(",");
console.log(res);
for (var i = 0; i < res.length; i++) {
if (pathname != res[i]) {
alert("IS NOT EQUAL");
//res.push(pathname);
//var joinedArray = res.join(",");
//console.log(joinedArray);
//createCookie('vid_cookies',joinedArray,7);
//var z = readCookie('vid_cookies');
//console.log(z)
}
}
} else {
jsonObj.push(pathname);
createCookie('vid_cookies',jsonObj,7);
}
//alert(jsonObj);
</script>
Here is the Array as :
["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.
In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n elements, n - 1 will not match.
One way to do it would be to use Array#every:
if (res.every(x => x !== pathname)) {
// add to array and set cookie
}
Alternatively you could convert the array to a Set, always add the value and set the cookie. The Set will automatically dedupe the values:
var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);
I am working on a real estate website. I have many ads in my website and I need to create a 'favorite' or 'save' button on each of the posts that will save the selected posts in a certain page for user to read later.
I want to use cookies or local storage to keep user favorites on that computer, which would allow users to add items to their favorites and see them again when they return. No account required.
Thanks to one of my friends, I wrote some code but it does not work properly - I mean it does not show any result.
BIG THANKS TO ANYONE THAT CAN HELP!
Here is my current code:
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
$(function(){
var faves = new Array();
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
faves = myfaves;
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.title+'</h4> Open page '+
'Remove me';
$('#appendfavs').append(element);
});
});
Add me to fav
<ul id="appendfavs">
</ul>
I would recommend to prefer the storage of the favorites via the local storage and fall back to to cookies if local storage is no available.
So I implemented a short example how to to use the local storage based on your example.
var chance;
var favorites;
var storage;
$(document).ready(function() {
chance = new Chance(); // Just for random hash generation
if (window.Storage != undefined) {
storage = window.localStorage;
if (storage.favorites == undefined) {
favorites = [];
} else {
favorites = JSON.parse(storage.favorites);
}
updateList();
$('#fav').click(function() {
addFavorite(window.location);
updateList();
});
$('#list').on('click', 'li a', function() {
deleteFavorite($(this).data('id'));
updateList();
});
} else {
// No support for local storage
// Fall back to cookies or session based storage
}
});
function addFavorite(url) {
favorites.push({
id: chance.hash({
length: 15
}),
url: url
});
storage.setItem('favorites', JSON.stringify(favorites));
}
function deleteFavorite(id) {
for (var i in favorites) {
if (favorites[i].id == id) {
favorites.splice(i, 1);
}
}
storage.setItem('favorites', JSON.stringify(favorites));
}
function updateList() {
$('#list').empty();
if (typeof favorites !== 'undefined' && favorites.length > 0) {
for (var i in favorites) {
$('#list').append('<li>' +
favorites[i].url.href +
' ' +
'<a class="delete" href="#" data-id="' + favorites[i].id + '">delete</a>' +
'</li>');
}
} else {
$('#list').append('<li>Nothing stored!</li>');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.3/chance.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="fav" href="#">Add</a>
<ul id="list">
</ul>
EDIT: Added JsFiddle link: https://jsfiddle.net/Wachiwi/r2r3097q/13/
(I read a few threads on the subject but did not find a working solution.)
On my page, I have a "Load more" button that triggers an Ajax call to get new portion of items to display. I would like to preserve these dynamically appended elements when the user gets to different page and then hits "Back" or "Forward" button of the browser - however I cannot get it to work.
I tried setting cache: true for the jQuery $.ajax() request. I also played around with the "Expires" and "Cache-Control" headers on the request, but no success. I consider keeping the dynamic content in <input type="hidden"> and listening to onLoad event in my jQuery script.
Any advice on how I can keep/cache the appended elements every time they're dynamically loaded?
UPDATE:
What I need to "remember" is HTML structure, so possibly a lot of characters (imagine if the user hits "Load more" 10 times and then leaves the page). So the size of any storage needs to be considered.
Here is an example of what I commented above. I think, in your case, it is useful. If this way is unviable you should consider to use a server side workaround. Check jsFiddle.
$(function(){
var clicked_times = 0;
$('button').on('click', function(){
// ajax....
// ajax success:
clicked_times++;
$('<p>new content</p>').insertBefore($(this));
});
window.onbeforeunload = function(){
if( clicked_times > 0 ) Cookies.Set('reload_contents', clicked_times);
};
if( Cookies.Check('reload_contents') ){
var times = Cookies.Get('reload_contents');
for( var i = 0; i < times; i++){
$('button').trigger('click');
}
Cookies.Set('reload_contents', '', -1);
}
});
/** Cookie methods */
var Cookies = {
Check: function (name) {
return !!this.Get(name);
},
Get: function (name) {
var n, ca, c;
n = name + "=";
ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length + 1, c.length);
}
return false;
},
Set: function (name, value, expire, options) {
var d = new Date(), expires;
var defaults = { expire_in: 'days', path: '/' };
if (typeof options !== "undefined") $.extend(true, defaults, options);
if (expire !== undefined && expire !== null) {
if (defaults.expire_in == 'days') d.setDate(d.getDate() + expire);
else if (defaults.expire_in == 'minutes') d.setDate(d.getTime() + expire * 1000);
else {
return false;
}
expires = "expires=" + d.toGMTString();
}
else expires = expires = "";
document.cookie = name + "=" + value + "; " + expires + '; path=' + defaults.path;
return true;
}
};
Use the browsers history. Try that (don't know about its crossbrowser-ability):
var url = "http://newurl.com";// you could save only hashes too.
if (/*url &&*/ location.url != url && history.replaceState) {
history.replaceState(null, url, url);
}
Greetings. André
looking to get the value after the domain but before anything else.
So an example of the URL would be:
www.domain.com/following#2
I only want to get the word following out of that url.
Currently have this which redirects a user and gets data after any fragments etc:
// First get the page URL and split it via # and ? signs
var parts = location.href.split('#');
var queryParameters = location.search.split('?');
// Now we get the value of the page value in the URL if there is one
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
// Next we check how many parts there are in the URL and if this a value, we add it to the current page
// and redirect to that new page number
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '?';
}
var newPageNumber = parseInt(parts[1], 10) + parseInt(pageNumber, 10);
location.href = mark + 'page=' + newPageNumber;
}
So out of the URL, i need to change this line:
location.href = mark + 'page=' + newPageNumber;
To
location.href = following + mark + 'page=' + newPageNumber;
But i will use a variable instead of following depending on what i take from the URL.
Thanks.
You can try location.pathname. Doing this should return the "path" or whatever is after the backslash
You can use a regular expression to obtain that text:
var regex = /\/(.*)#/;
var url = 'www.domain.com/following#2';
var result = url.match(regex);
if (result.length > 0) {
console.log(result[result.length - 1]);
}
Disclaimer - this particular example won't work with http:// at the start of the URL, but I have used the URL from your question.
I have this script below that I'm using to set and read the last 5 viewed pages using JavaScript. The client does not want render any duplicate URL/Text, but I'm not having any luck with what I have tried so far.
Maybe I'm going about it all wrong. Any help would be appreciated.
// Set read, set & delete cookie functions-------------------------------------------------------------------------
function getCookie (cookie_name){
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
if (results) {
return ( unescape ( results[2] ) );
} else {
return null;
}
}
function setCookie (name,value,expiredays){
var exdate = new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie = name+"="+escape(value)+((expiredays==null)?"":";expires="+exdate.toGMTString());
}
function delete_cookie (cookie_name) {
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
// Set last 5 visited pages cookies --------------------------------------------------------------------------------
tlvp_the_last_visited_pages();
// function to get info from cookies for last five pages.
// Needs to be seperate from getCookie function for parsing reasons.
function fetchCookie(name){
if(document.cookie.length>0){
start = document.cookie.indexOf(name+"=");
if(start!=-1){
start = start+name.length+1;
end = document.cookie.indexOf(";",start);
if(end==-1){
end = document.cookie.length;
}
return unescape(document.cookie.substring(start,end));
}
}
return "";
}
function tlvp_the_last_visited_pages(){
tlvp_div = document.getElementById('the_last_visited_pages');
if(tlvp_pages_count > 0){
for(var i = tlvp_pages_count; i >= 0; i--){
if(i > 0){
setCookie("tlvp_visited_page"+i+"_link",fetchCookie("tlvp_visited_page"+(i-1)+"_link"),tlvp_expiredays);
setCookie("tlvp_visited_page"+i+"_title",fetchCookie("tlvp_visited_page"+(i-1)+"_title"),tlvp_expiredays);
} else {
setCookie("tlvp_visited_page"+i+"_link",document.URL,tlvp_expiredays);
setCookie("tlvp_visited_page"+i+"_title",document.title,tlvp_expiredays);
}
}
}
// This is where the code is created for the div...
tlvp_last_visited_pages_title = document.createElement("div");
tlvp_last_visited_pages_title.className = "tlvp_title";
tlvp_last_visited_pages_title_text = document.createTextNode(tlvp_title);
tlvp_last_visited_pages_title.appendChild(tlvp_last_visited_pages_title_text);
tlvp_div.appendChild(tlvp_last_visited_pages_title);
tlvp_last_visited_pages_content = document.createElement("div");
tlvp_last_visited_pages_content.className = "tlvp_content";
// Loops through the cookies and creates text links...
for(var i=1; i<=tlvp_pages_count; i++){
var e = fetchCookie("tlvp_visited_page"+i+"_link");
if (e != "") {
tlvp_visited_page_line = document.createElement("p");
tlvp_visited_page_a = document.createElement("a");
tlvp_visited_page_a.href = getCookie("tlvp_visited_page"+i+"_link");
tlvp_visited_page_text = document.createTextNode(getCookie("tlvp_visited_page"+i+"_title"));
tlvp_visited_page_a.appendChild(tlvp_visited_page_text);
tlvp_visited_page_line.appendChild(tlvp_visited_page_a);
tlvp_last_visited_pages_content.appendChild(tlvp_visited_page_line);
}
}
tlvp_div.appendChild(tlvp_last_visited_pages_content);
}
You could try storing the values as JSON in one cookie.
// Set read, set & delete cookie functions-------------------------------------------------------------------------
function getCookie (cookie_name){
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
if (results) {
return ( unescape ( results[2] ) );
} else {
return null;
}
}
function setCookie (name,value,expiredays){
var exdate = new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie = name+"="+escape(value)+((expiredays==null)?"":";expires="+exdate.toGMTString());
}
function delete_cookie (cookie_name) {
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
// Set last 5 visited pages cookies --------------------------------------------------------------------------------
function last_visited() {
var max_urls = 5;
var cookie = getCookie("last_visited");
var url = window.location.href;
// Get the JSON cookie or a new array.
var urls = (cookie != null) ? JSON.parse(cookie) : [];
// Build new_urls out of history that is not this url.
var new_urls = [];
for (var i=0; i < urls.length; i++) {
if (urls[i].url != url) {
new_urls.push(urls[i]);
}
}
// remove the last item if the array is full.
if (new_urls.length == max_urls) {
new_urls.pop();
}
// Add this url to the front.
new_urls.unshift({url: url, title: document.title});
// Save it
setCookie("last_visited", JSON.stringify(new_urls),1);
// Create html
var html = "<ul>\n";
for (var i = 0; i < new_urls.length; i++) {
html += "<li>" + new_urls[i].title + "</li>\n"
}
html += "</ul>\n";
// Render html.
var el = document.getElementById("last_visited");
el.innerHTML = html;
}
window.onload = function () {
last_visited();
};